前面提到过,派生类的默认复制构造函数会调用基类的复制构造函数,以对派生类对象中的基类对象进行初始化。
如果基类重载了赋值运算符=而派生类没有,那么在派生类对象之间赋值,或用派生类对象对基类对象进行赋值时,其中基类部分的赋值操作是调用被基类重载的=完成的。例如下面的程序:
#include <iostream>
using namespace std;
class CBase
{
public:
CBase() {}
CBase(CBase & c) { cout << "CBase::copy constructor called" << endl; }
CBase & operator = (const CBase & b)
{
cout << "CBase::opeartor = called" << endl;
return *this;
}
};
class CDerived : public CBase {};
int main()
{
CDerived d1, d2;
CDerived d3(d1); //d3初始化过程中会调用CBase类的复制构造函数
d2 = d1; //会调用CBase类重载的“=”运算符
return 0;
}
程序的输出结果是:
CBase::copy constructor called
CBase::opeartor = called