條款12 複製物件時勿忘其每乙個成分

2021-08-09 12:27:55 字數 799 閱讀 9326

// 條款12: 複製物件時勿忘記其每乙個成分

// 這裡將copy建構函式和copy assignment操作符統稱為copying函式。

// 1.copying函式應該確保複製「物件內的所有成員變數」及「所有base class成分」。

// 2.不要嘗試以某個copying函式實現另乙個copying函式。應該將共同機能放進第三個函式中,

// 並由兩個copying函式共同呼叫。copy建構函式和copy assignment操作符兩個之間的互相呼叫

// 是沒有任何意義的,乙個用來構造新的物件,另乙個用來給物件賦值。

#include #include class customer

customer(const customer& rhs) : name_(rhs.name_)

customer& operator=(const customer& rhs)

private:

std::string name_;

};class prioritycustomer : public customer

prioritycustomer(const prioritycustomer& rhs)

: customer(rhs), priority_(rhs.priority_)

prioritycustomer& operator=(const prioritycustomer& rhs)

private:

int priority_;

};int main()

條款12 複製物件時勿忘其每乙個成分

effective c 第三版 當你編寫乙個copying函式,請確保 1 複製所有local成員變數 2 呼叫所有base classes內的適當的copying函式。令copy assignment操作函式呼叫copy建構函式是不合理的,因為這就像是圖構造乙個已經存在的物件。反方向,令copy構...

條款12 複製物件時勿忘其每乙個成分

如果你宣告自己的copying函式 拒絕編譯器的預設實現 當你為class新增乙個成員變數,你必須同時修改copying函式 也需要修改class的所有建構函式及任何非標準形式的operator 條款10有個例子 如果你忘記,編譯器不會告訴你。copying函式應該確保複製 物件內的所有成員變數 及...

條款12 複製物件時勿忘其每乙個成分

1.當你寫好copying系列函式的時候,如果你為class新增乙個成員函式,你必須同時修改copying函式 你也需要修改class的所有建構函式以及任何非標準形式的operator 如果你忘記了,編譯器不太可能提醒你。2.當發生繼承的時候,任何時候只要你承擔起為derived class撰寫co...