我想使用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