Remember:
The copy function should ensure that all member variables within the object and all parent components are copied.
Do not attempt to implement another copy function with one copy function. Common functions should be placed in a third function and called together by two copy functions.
The following is a class that implements its own copy function, together with normal.
voidLogcall (Const string&funcName);classCustomer { Public: ... Customer (Constcustomer&RHS); Customer&operator=(Constcustomer&RHS); ...Private: stringname;}; Customer::customer (Constcustomer&RHS): Name (rhs.name) {Logcall ("Customer Copy Constructor")}customer& Customer::operator=(Constcustomer&RHS) {Logcall ("Customer copy assignment operator"); Name=Rhs.name; return* This;}
But if you add a member variable for class, you must modify the copy function at the same time. If you forget, the compiler will not remind you.
class Date {...}; class Customer {public: ... Private : string name; Date lasttransaction;} ;
In addition, if inheritance occurs, you should have the copy function of the subclass call the corresponding parent class function.
classPrioritycustomer: Publiccustomer{ Public: ... Prioritycustomer (Constprioritycustomer&RHS); Prioritycustomer&operator=(Constprioritycustomer&RHS); ...Private: intPriority ;}; Prioritycustomer::P Rioritycustomer (Constprioritycustomer&RHS): Customer (RHS), priority (Rhs.priority)//call the copy constructor of the parent class{Logcall ("Prioritycustomer Copy Constructor")}prioritycustomer& Prioritycustomer::operator=(Constprioritycustomer&RHS) {Logcall ("Prioritycustomer copy assignment operator"); Customer::operator= (RHS);//assigning the parent component to a valuePriority =rhs.priority; return* This;}
Effective C + + clause 12: Do not forget every ingredient when copying an object