我想使用C++ 11的構造函數繼承特性。下面的代碼段(從某處複製,我不記得從那裏)的作品完全沒問題:刪除複製構造函數break繼承構造函數
#include <iostream>
struct Base {
Base() : Base(0) {}
Base(int a) : Base(a, 0) {}
Base(int a, double b) { std::cout << "Base(" << a << "," << b << ")" << std::endl; }
};
struct Derived : Base {
using Base::Base;
Derived(const Derived& that) = delete; // This line is the culprit
};
int main(int argc, char* argv[]) {
Derived d1;
Derived d2(42);
Derived d3(42, 3.14);
}
也就是說,直到由註釋標記的代碼行被添加;因爲那樣的話,所有的地獄破散:
> g++ -std=c++11 -o test test.cpp
test.cpp: In function ‘int main(int, char**)’:
test.cpp:18:11: error: no matching function for call to ‘Derived::Derived()’
Derived d1;
^
test.cpp:18:11: note: candidates are:
test.cpp:13:16: note: Derived::Derived(int)
using Base::Base;
^
test.cpp:13:16: note: candidate expects 1 argument, 0 provided
test.cpp:13:16: note: Derived::Derived(int, double)
test.cpp:13:16: note: candidate expects 2 arguments, 0 provided
看來,如果刪除拷貝構造函數也不知怎地Base
人跡罕至成爲默認的構造函數。谷歌搜索這個問題沒有提出任何有用的東西; SO建議this issue,但據我瞭解,我不在這個片段中使用複製初始化。有人能對這裏發生的事情有所瞭解嗎?
(生成上述消息編譯器是GCC 4.8.2;然而,鐺返回類似的錯誤消息)
默認的構造函數沒有被繼承。 –
T.C.怎麼會這樣?在Derived d1;行中,我清楚地看到調用了Base()。 –
@ T.C。詞的選擇是誤導性的。當然,構造函數是繼承的 - 否則,你將無法從派生類中調用它們。它只用於不同的課程。 – SergeyA