本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
经验1:copying函数应该确保复制“对象内的所有成员变量”及”所有base class成分“。
示例:没对base class成分赋值
<pre name="code" class="cpp">#include <iostream> #include <string> using namespace std; class Customer{ public: Customer(){ } Customer(string n):name(n){} Customer(const Customer &rhs) : name(rhs.name){ } Customer &operator=(const Customer &rhs){ name = rhs.name; return *this; } string getCustomer() const{return name;} private: std::string name; }; class PriorityCustomer: public Customer{ public: PriorityCustomer(int p, string n):Customer(n), priority(p){} PriorityCustomer(const PriorityCustomer &rhs): priority(rhs.priority){//derived class为调用base class的默认构造函数初始化 } PriorityCustomer &operator=(const PriorityCustomer &rhs){ //没对base class成分进行赋值 priority = rhs.priority; return *this; } int getPriority() const {return priority;} string getCustermerName() const{return getCustermerName();} private: int priority; }; int main(){ PriorityCustomer pc1(1, "PriorityCustomer 1"); PriorityCustomer pc2(pc1); PriorityCustomer pc3; pc3 = pc1; cout << pc2.getPriority() << endl << pc3.getPriority() << endl; cout << pc2.getCustomerName() << endl << pc3.getCustomerName() << endl; }
输出:
1
1
(空)
(空)
解析:
PriorityCustomer的copy构造函数和copyassignment函数没有指定参数传给它的base class构造函数,因此PriorityCustomer对象的Customer成分会被Customer的默认构造函数初始化,所以它的name成员变量为被初始化为空字符串
纠正:对base class成分赋值
#include <iostream> #include <string> using namespace std; class Customer{ public: Customer(){ } Customer(string n):name(n){} Customer(const Customer &rhs) : name(rhs.name){ } Customer &operator=(const Customer &rhs){ name = rhs.name; return *this; } string getName() const{return name;} private: std::string name; }; class PriorityCustomer: public Customer{ public: PriorityCustomer(){} PriorityCustomer(int p, string n):Customer(n), priority(p){} PriorityCustomer(const PriorityCustomer &rhs): Customer(rhs),priority(rhs.priority){//调用base class的copy构造函数 } PriorityCustomer &operator=(const PriorityCustomer &rhs){ Customer::operator=(rhs); //对base class成分进行赋值动作 priority = rhs.priority; return *this; } int getPriority() const {return priority;} string getCustomerName() const{return getName();} private: int priority; }; int main(){ PriorityCustomer pc1(1, "PriorityCustomer 1"); PriorityCustomer pc2(pc1); PriorityCustomer pc3; pc3 = pc1; cout << pc2.getPriority() << endl << pc3.getPriority() << endl; cout << pc2.getCustomerName() << endl << pc3.getCustomerName() << endl; system("pause"); }输出:
解析:
当你编写一个copying函数(包括copyconstructor和copy assignment)时,请确保(1)复制所有local成员变量,(2)调用所有base classes内的适当的copying函数
经验2:不要尝试以某个copying函数实现另一个copying函数。应该将共同机能放进第三个函数中,并由两个copying函数共同调用。