Effective C++ 條款12:複製物件時勿忘其每一個成分 學習筆記
阿新 • • 發佈:2019-01-02
Effective C++ 條款12:複製物件時勿忘其每一個成分
<textarea readonly="readonly" nam ="code" class="c++"> void logCall(const string& funcName); class Customer{ public: Customer(string b):name(b){} Customer(const Customer& rhs); Customer& operator = (const Customer& rhs); string name;//將成員變數宣告為public便於實驗觀察 }; void logCall(const string &funcName){ cout << "funcName = " << funcName << endl; } Customer::Customer(const Customer &rhs):name(rhs.name){ logCall("Customer copy constructor."); } Customer& Customer::operator = (const Customer& rhs){ logCall("Customer copy assignment operator."); name = rhs.name; return *this; } class PriorityCustomer:public Customer{ public: PriorityCustomer(int a, string b):Customer(b),priority(a){} PriorityCustomer(const PriorityCustomer& rhs); PriorityCustomer& operator = (const PriorityCustomer& rhs); int priority;//將成員變數宣告為public便於實驗觀察 }; // 拷貝建構函式中 Customer(rhs) 編譯器強制要求加上,在拷貝賦值函式中沒有向基類傳遞資訊,作為對比 PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs) :Customer(rhs), priority(rhs.priority){ logCall("PriorityCustomer copy constructor."); } PriorityCustomer& PriorityCustomer::operator =(const PriorityCustomer& rhs){ logCall("PriorityCustomer assignment operator."); priority = rhs.priority; return *this; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); PriorityCustomer pc1(10,"Hello"); PriorityCustomer pc2(100,"World"); PriorityCustomer pc3(pc2); pc1 = pc2; cout<<"pc3.priority = "<<pc3.priority<<endl; cout<<"pc3.name = "<<pc3.name<<endl; cout<<"pc1.priority = "<<pc1.priority<<endl; cout<<"pc1.name = "<<pc1.name<<endl; return a.exec(); } </textarea>
此時得到的結果是
可見拷貝建構函式複製了每一個成員,而拷貝賦值函式並沒有全部複製。對拷貝賦值函式進行修改,加入基類的拷貝賦值函式:
最終得到的結果是<textarea readonly="readonly" nam ="code" class="c++"> PriorityCustomer& PriorityCustomer::operator =(const PriorityCustomer& rhs){ logCall("PriorityCustomer assignment operator."); Customer::operator =(rhs); priority = rhs.priority; return *this; } </textarea>