【问题标题】:C++ inherited copy constructor call ?C++ 继承的复制构造函数调用?
【发布时间】:2012-09-20 08:46:35
【问题描述】:

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

当我为 B 类调用复制构造函数时,是否会自动调用此复制构造函数?或者如何做到这一点?这是好方法吗:

A::A(A* a)
{
    B(a);
    // copy stuff
}

谢谢!

【问题讨论】:

  • 那不是拷贝构造函数。

标签: c++ constructor copy copy-constructor


【解决方案1】:

复制构造函数具有签名:

A(const A& other)  //preferred 

A(A& other)

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

B(const B& other) { }

等价于

B(const B& other) : A() { }

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

B(const B& other) : A(other) { }

【讨论】:

    【解决方案2】:

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

    B::B(const B& b) : A(b)
    {
        // copy stuff
    }
    

    我对语法做了相当多的修改,因为您的代码没有显示复制构造函数,并且与您的描述不符。

    不要忘记,如果您自己实现复制构造函数,您应该遵循rule of three

    【讨论】:

    • ...或五规则,如果编写 C++11(应该已经在编写)。
    猜你喜欢
    • 2019-01-12
    • 2015-11-16
    • 2014-06-15
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多