条款:12 复制对象时勿忘其每一个成分

(一)

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函数共同调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值