Eli*_*iad 3 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;
}
Run Code Online (Sandbox Code Playgroud)
现在为什么Abstract()
在构造Abstract( const Abstract& other )
时调用而不是复制构造childCopy
函数?
不应该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
{ }
Run Code Online (Sandbox Code Playgroud)