C ++默认构造函数未使用"using"继承.当存在移动和复制构造函数时 [英] C++ Default constructor not inherited with "using" when move and copy constructors present
问题描述
class A{
public:
A(){};
};
class B : public A{
public:
using A::A;
B(const B&) = default;
B( B&&) = default;
};
B b;
编译器(g ++(5.4.0-6ubuntu1)/c ++ 11)说对B :: B()的调用没有匹配函数",并列出了复制和移动构造函数作为候选对象.如果我将那些默认值注释掉,它将进行编译.是什么原因造成的?明确指定它们为默认值有什么区别?如果那两条线不在那儿,它们将仍然是默认值.
The compiler (g++ (5.4.0-6ubuntu1) / c++11) says "no matching function for call to B::B()" and lists the copy and move constructors as candidates. If I comment those defaulted ones out then it compiles. What causes this? And what difference does it make that they are explicitly defaulted? If those 2 lines weren't there they would be defaulted anyway.
推荐答案
Before C++17, the default constructor of the base class won't be inherited via using
:
不是默认构造函数或复制/移动构造函数且其签名与派生类中用户定义的构造函数不匹配的所有候选继承的构造函数均在派生类中隐式声明. (直到C ++ 17)
All candidate inherited constructors that aren't the default constructor or the copy/move constructor and whose signatures do not match user-defined constructors in the derived class, are implicitly declared in the derived class. (until C++17)
在C ++ 17之后,代码可以正常工作.
After C++17 the code works fine.
在此之前,默认构造函数不会从基类继承,也不会是,因为提供了复制/移动构造函数.
Before that, the default constructor won't be inherited from the base class, and won't be generated for class B
because copy/move constructor are provided.
如果没有为类类型(结构,类或联合)提供用户声明的任何类型的构造函数,则编译器将始终将默认构造函数声明为其类的内联公共成员.
If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.
这就是为什么如果您注释掉复制/移出构造函数,它将编译的原因.您可以将定义明确添加为C ++ 17之前的解决方法.例如
That's why if you comment copy/move constructor out it compiles. You can add the definition explicitly as a pre-C++17 workaround. e.g.
class B : public A {
public:
B(const B&) = default;
B( B&&) = default;
B() = default;
};
代码使用 gcc8 进行编译.
The code compiles with gcc8.
这篇关于C ++默认构造函数未使用"using"继承.当存在移动和复制构造函数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!