【发布时间】:2015-10-05 17:46:55
【问题描述】:
我正在尝试使用 C++11 的构造函数继承特性。以下 sn-p (从某处复制,我不记得从哪里复制的)完全可以正常工作:
#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,但据我了解,我在这个sn-p中没有使用复制初始化。有人能解释一下这里发生了什么吗?
(生成上述消息的编译器是 GCC 4.8.2;但是,clang 会返回类似的错误消息。)
【问题讨论】:
-
不继承默认构造函数。
-
T.C.怎么会这样?在
Derived d1;行中,我清楚地看到Base()被调用。 -
@T.C.词语的选择具有误导性。当然,构造函数是继承的——否则,您将无法从派生类调用它们。它只是用于不同的类。
标签: c++ c++11 inheritance constructor copy-constructor