考虑以下代码:
class TBase {
public:
TBase();
TBase(const TBase &);
};
class TDerived: public TBase {
public:
using TBase::TBase;
};
void f() {
TBase Base;
TDerived Derived(Base); // <=== ERROR
}
所以,我有基类和派生类,并希望使用“使用 TBase::TBase”从基类中提取复制构造函数,以便能够以这种方式创建派生类的实例:
TDerived Derived(Base);
但是 all compilers 拒绝了这些错误消息
7 : note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'TBase' to 'const TDerived' for 1st argument
为什么?我究竟做错了什么?为什么“使用 TBase::TBase”在这种情况下不起作用?
更新
如何解释以下来自 cppreference.com 的代码?
struct B1 {
B1(int);
};
struct D1 : B1 {
using B1::B1;
// The set of inherited constructors is
// 1. B1(const B1&)
// 2. B1(B1&&)
// 3. B1(int)
最佳答案
复制和移动构造函数(和默认构造函数)永远不会被继承,仅仅因为标准是这样说的。所有其他构造函数都是。
对 cppreference 的评论具有误导性(1)。标准中的相同评论说:
(强调我的)。
然后标准继续说实际上只有 D1(int)
构造函数被继承。 D1
的复制和移动构造函数与任何其他类一样隐式声明,而不是继承。
有关详细信息,请参阅 C++14 12.9 [class.inhctor]。
(1) 我提交了对 cppreference 的更改,希望能澄清这一点。
关于C++,继承的copy ctors 不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37585945/