您的位置:首页 > 编程语言 > C语言/C++

Effective C++:规定12:不要忘了复制的对象时,它的每一个组成部分

2015-08-08 12:54 316 查看
(一个)

继承制度的声明:

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函数。请确保(1)复制全部local成员变量!(2)调用全部base classes内的适当的copying函数。

(二)这两个函数都不能够互相调用!

我们不该令copy assignment操作符调用copy构造函数。

这不合理。由于这就像试图构造一个已经存在的对象。

我们也不该令copy构造函数调用copy assignment操作符。由于构造函数是用来初始化的,而copy assignment操作符仅仅作用于已经初始化的对象身上。对一个尚未初始化好的对象进行赋值。无聊的一笔啊!

假设真的非常想避免代码反复,那么在这两个函数之间仅仅有一种办法!

建立一个新的成员函数给两者调用。这个函数往往是在private中。而且往往命名为:init。

请记住:

(1)copying函数应该确保复制“对象内的全部成员变量”及“全部base classes成分”。

(2)不要尝试以某个copying函数实现另外一个copying函数。应该将共同机能放进第三个函数中,并由两个copying函数共同调用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: