复制对象时,勿忘其每个成分
作者在本节条款提醒我们,在多重继承的情况下进行copy或者copy assignment 的operator=的编写时,一定要考虑base 类部分数据的初始化后者复制。
对照一下代码:
class Cutsomer
{
……
private:
string name;
string telphone;
};
class PriorityCustomer:public Cutsomer
{
public:
PriorityCustomer()
{
cout<<"PriorityCustomer Ctor"<<endl;
}
PriorityCustomer(const PriorityCustomer& rhs)
:priority(rhs.priority)
{
cout<<"PriorityCustomer Copy Ctor"<<endl;
}
PriorityCustomer& operator=(const PriorityCustomer& rhs)
{
cout<<"PriorityCustomer assign operator"<<endl;
priority=rhs.priority;
return *this;
}
private:
int priority;
};
PriorityCustomer中的数据有下面
int priority;
string name;
string telphone;
而真正copy或者copy assignment的时候仅仅处理了int priority;
我们能够看到上面的代码中忽视了base类部分的数据的处理。这时改动代码例如以下:
PriorityCustomer(const PriorityCustomer& rhs)
:Cutsomer(rhs),priority(rhs.priority)
{
cout<<"PriorityCustomer Copy Ctor"<<endl;
}
PriorityCustomer& operator=(const PriorityCustomer& rhs)
{
cout<<"PriorityCustomer assign operator"<<endl;
Cutsomer::operator=(rhs);
priority=rhs.priority;
return *this;
}