如您在下面的代码中所见,我有三个类。请注意我是如何编写复制构造函数的。
#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/