(一)
class Date {...};
class Customer {
public:
...
private:
string name;
Date lastTransaction;
};
class PriorityCustomer : public Customer {
public:
PriorityCustomer(const PriorityCustomer& rhs);
PriorityCustomer& operator=(const PriorityCustomer& rhs);
private:
int priority;
};
任何时候,我们承担起“为derived class撰写copying函数“的重大责任必须很小心复制其 base class成分。那些成分旺旺是private的。所以无法直接访问它们,应该让derived class 的copying函数调用相应的base class函数:
PriorityCustomer::PriorityCustomer(const PriorityCustomer &rhs) : Customer(rhs), priority(rhs.priority)
{
}
PriorityCustomer& PriorityCustomer::operator =(const PriorityCustomer &rhs)
{
Customer::operator=(rhs);
priority = rhs.priority;
return *this;
}
结论:当我们编写一个copying函数的时候,确保基类复制所有local成员变量,子类调用所有基类内的适当的copying函数。
(二)
想要避免 copying assignment 操作符和copy 构造函数重复代码,只有一种办法:
建立衣蛾新的成员函数,给两者调用。这个函数往往在private中。并且命名为:init
请记住:
1 copying函数应该确保复制”对象内所有的成员变量“以及”所有base classes成分“
2不要尝试以某个copying函数实现另外一个copying函数。应该将共同技能放进第三个函数中。并有两个copying函数共同调用。