【发布时间】:2015-06-09 23:11:58
【问题描述】:
正如您在下面的代码中看到的那样,我有三个类。请注意我是如何编写复制构造函数的。
#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)吗?
【问题讨论】:
-
你怎么知道
Parent(other)没有被调用?请在每个构造函数主体中添加几个printfs 或cout <<s 以查看调用的内容。请用结果更新问题。 -
请让所有构造函数初始化同一个类中定义的所有数据成员,例如
Abstract(): mA(-1) {}; -
虚拟基类只能由最派生类初始化。其他构造函数调用被忽略并替换为默认构造函数调用。
-
@0x499602D2:应该作为答案发布。
标签: c++ class copy-constructor