C++继承了复制构造函数调用?

kir*_*off 3 c++ constructor copy copy-constructor

我有从类A派生的类B.我调用了我为类B的对象实现自己的复制构造函数.我还为类A实现了自己的构造函数.

当我为B类调用复制构造函数时,是否会自动调用此复制构造函数?或者怎么做?这是好方法:

A::A(A* a)
{
    B(a);
    // copy stuff
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jon*_*Jon 19

您可以使用构造函数初始化列表执行此操作,如下所示:

B::B(const B& b) : A(b)
{
    // copy stuff
}
Run Code Online (Sandbox Code Playgroud)

我修改了语法很多,因为您的代码没有显示复制构造函数,并且它与您的描述不一致.

不要忘记,如果您自己实现复制构造函数,则应遵循三条规则.

  • ...或者五条规则,如果编写C++ 11(哪一个应该已经写了). (3认同)

Luc*_*ore 5

复制构造函数具有以下签名:

A(const A& other)  //preferred 
Run Code Online (Sandbox Code Playgroud)

或者

A(A& other)
Run Code Online (Sandbox Code Playgroud)

你的是一个转换构造函数。除此之外,您需要显式调用基类的复制构造函数,否则将调用默认构造函数:

B(const B& other) { }
Run Code Online (Sandbox Code Playgroud)

相当于

B(const B& other) : A() { }
Run Code Online (Sandbox Code Playgroud)

即不会自动调用类 A 中的复制构造函数。你需要:

B(const B& other) : A(other) { }
Run Code Online (Sandbox Code Playgroud)