复制对象时,勿忘其每一个成分
作者在本节条款提醒我们,在多重继承的情况下进行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;
}
时间: 2024-11-02 16:47:25