設計良好的面向對象系統會將對象的內部封裝起來,只留兩個函數負責對象拷貝,即copy構造函數與copy assignment操作符。編譯器會在必要的時候為類創建coping函數,並說明這些“編譯器生成版”的行為:將被拷貝對象的所有成員變量都做一份拷貝。
任何時候,只要自己實現派生類的copying函數,則必須很小心的復制其基類成分。這些成分往往是private私有的,故無法直接訪問它們,因此應該讓派送類的coping函數調用相應的基類函數:
void logCall(const string& funcName);
class Customer { public:
... Customer(const Customer& rhs); Customer& operator=(const Customer& rhs);
... private: string name; Date lastTranscation; };
class PriorityCustomer : public Customer { public: ... PriorityCustomer(const PriorityCustomer& rhs); PriorityCustomer& operator=(const PriorityCustomer& rhs); ... private: int priority; }; PriorityCustomer ::PriorityCustomer (const PriorityCustomer& rhs) : Customer(rhs), //調用基類的copy構造函數 priority(rhs.priority) { logCall("PriorityCustomer copy constructor"); } PriorityCustomer& PriorityCustomer ::operator = (const PriorityCustomer& rhs) { logCall("PriorityCustomer copy assignment constructor"); Customer::operator=(rhs); //對基類Customer成分進行復制動作 priority = rhs.priority; return *this; }