1. 程式人生 > >條款12:賦值物件時勿忘記其每一個成分

條款12:賦值物件時勿忘記其每一個成分

如果你宣告自己的copying函式,當你你的程式碼出錯時編譯器不會告訴你

void logCall(const string& funcName)
{
    cout << funcName << endl;
}

class Customer
{
public:
    Customer(const string& str) :name(str)
    {

    }
    Customer(const Customer& rhs):name(rhs.name)
    {
        logCall("Customer copy Customer"
); } Customer& operator=(const Customer& rhs) { logCall("Customer copy assignment operator"); name = this->name; return *this; } private: string name; }; Customer c("Hello"); Customer a(c); //上述程式碼看起來很好,直到另一個成員變數加入改變了格局 class Date { } class Customer { public
: private: string name; Date lastTransaction; }; /* 上面的程式碼增加了成員變數lastTransaction,copying函式執行 的是區域性拷貝,複製了顧客的name但是沒有複製新新增的lastTransaction。 */ class PriorityCustomer :public Customer { public: PriorityCustomer() { } PriorityCustomer(const PriorityCustomer& rhs):priority(rhs.priority) { logCall("PriorityCustomer copy constructor"
); } PriorityCustomer& operator=(const PriorityCustomer& rhs) { logCall("PriorityCustomer copy assignment constructor"); priority = rhs.priority; return *this; } private: int priority=1; }; PriorityCustomer a; PriorityCustomer b(a); /* 上面的程式碼發生了繼承,PriorityCustomer的 copying函式自己申明的成員變數,但是每個PriorityCustomer 還包含所繼承Customer的成員變數,這些成員變數未複製。 */ PriorityCustomer(const PriorityCustomer& rhs):priority(rhs.priority),Customer(rhs) { logCall("PriorityCustomer copy constructor"); } PriorityCustomer& operator=(const PriorityCustomer& rhs) { logCall("PriorityCustomer copy assignment constructor"); Customer::operator=(rhs); priority = rhs.priority; return *this; } /* 當你為derived class撰寫copying函式時,你也要承擔 複製base class成分的責任, */