C++ 虚拟基类 : parent's copy constructor doesn't get called

标签 c++ class copy-constructor

如您在下面的代码中所见,我有三个类。请注意我是如何编写复制构造函数的。

#include <iostream>

class Abstract
{
public:
    Abstract(){};
    Abstract( const Abstract& other ): mA(other.mA){};
    virtual ~Abstract(){};

    void setA(double inA){mA = inA;};
    double getA(){return mA;};

    virtual void isAbstract() = 0;
protected:
    double mA;
};

class Parent : public virtual Abstract
{
public:
    Parent(){};
    Parent( const Parent& other ): Abstract(other){};
    virtual ~Parent(){};

};


class Child : public virtual Parent
{
public:
    Child(){};
    Child( const Child& other ): Parent(other){};
    virtual ~Child(){};

    void isAbstract(){};
};


int main()
{
    Child child1;
    child1.setA(5);

    Child childCopy(child1);
    std::cout << childCopy.getA() << std::endl;
    return 0;
}

现在为什么在构造 childCopy 时调用 Abstract() 而不是复制构造函数 Abstract( const Abstract& other )

Child(other) 不应该调用 Parent(other) 吗? Parent(other) 不应该依次调用 Abstract(other) 吗?

最佳答案

虚基类只能由最派生类初始化。从非最派生类调用虚拟基类的构造函数将被忽略,并替换为默认构造函数调用。这是为了确保虚拟基础子对象只被初始化一次:

正确的代码应该将构造函数调用放在最派生类的ctor-initializer中:

Child(Child const& other)
    : Abstract(other) // indirect virtual bases are
                      // initialized first
    , Parent(other) // followed by direct bases
{ }

关于C++ 虚拟基类 : parent's copy constructor doesn't get called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30744416/

相关文章:

c++ - 在对象(不是指针)的 std::vector 上调用 push_back 有严重的副作用。那么指针会更好吗?

c++ - 关于包含不可复制成员引用的类的复制构造函数的建议

c++ - 错误地将字符串传递给 printf 样式日志函数时丢失错误

c++ - 在 C++ 中将 uint8_t 数组转换为字符串

c# - 类型(类)作为占位符? (避免复制/粘贴)

c++ - 访问类中的结构成员

c++ - C++中的类存储保证

c++ - 复制嵌套 vector 的最简单方法是什么

c++ - 右值和左值引用的模板特化

c++ - 如何检查套接字是否已连接