void logCall(const std::string & funcName);
class Customer {
public:
Customer(const Customer & rhs);
Customer& operator= (const Customer& rhs);
private:
std::string name;
};
Customer::Customer(const Customer & rhs): name(rhs.name) {
logCall("Customer copy constructor");
}
Customer& Customer::operator=(const Cutomer& rhs) {
logCall("Customer copy assignment operator");
name = rhs.name; // 复制rhs的数据
name = rhs.name;
return *this;
}
但是如果添加一个新的成员变量, 如下
class Date{};
class Customer {
public:
// 同上
private:
std::string name;
Date lastTransaction;
};
这时既有copying函数执行的是局部拷贝(partial copy): 它们的确赋值了顾客的name, 但没有复制新添加的lastTransaction。同理, 如果出现继承, 更有危机。
class PriorityCustomer:public Customer {
public:
PriorityCustomer(const PriorityCutomer &rhs);
PriorityCustomer & operator=(const PriorityCutomer &rhs);
private:
int priority;
}
// 错误
PriorityCustomer::PriorityCustomer(const PriorityCustomer &rhs): priority(rhs.priority) {
logCall("PriorityCustomer copy constructor");
}
PriorityCustomer & PriorityCutomer::operator=(const PriorityCustomer &rhs) {
logCall("PriorityCustomer copy assignment operator");
priority =rhs.priority;
return *this;
}
// 正确
PriorityCustomer::PriorityCutomer(const PriorityCustomer& rhs): Customer(rhs), priority(rhs.priority) {
logCall("PriorityCustomer copy constructor");
}
PriorityCustomer & PriorityCustomer::operator=(const PriorityCustomer& rhs) {
logCall("PriorityCustomer copy assignment operator");
Customer::operator=(rhs);
priority = rhs.priority;
return *this;
}
总结:
- Copying函数应该确保赋值“对象内的所有成员变量”及“所有base class成分”。
- 不要尝试以某个copying函数实现另一个copying函数。 应该将共同机能放进第三个函数中, 并由两个copying函数共同调用。