1. 程式人生 > >Effective C++ 條款12

Effective C++ 條款12

tracking javascrip tex const cto copy operator hide ext

復制對象時,勿忘其每個成分

作者在本節條款提醒我們,在多重繼承的情況下進行copy或者copy assignment 的operator=的編寫時,一定要考慮base 類部分數據的初始化後者復制。

對照一下代碼:

class Cutsomer
{
……
private:
    string name;
    string telphone;
};


class PriorityCustomer:public Cutsomer
{
public:
    PriorityCustomer()
    {
        cout<<"PriorityCustomer Ctor"
<<endl; } PriorityCustomer(const PriorityCustomer& rhs) :priority(rhs.priority) { cout<<"PriorityCustomer Copy Ctor"<<endl; } PriorityCustomer& operator=(const PriorityCustomer& rhs) { cout<<"PriorityCustomer assign operator"
<<endl; priority=rhs.priority; return *this; } private: int priority; };

PriorityCustomer中的數據有下面

    int priority;
    string name;
    string telphone;

而真正copy或者copy assignment的時候僅僅處理了int priority;
我們能夠看到上面的代碼中忽視了base類部分的數據的處理。這時改動代碼例如以下:

PriorityCustomer(const
PriorityCustomer& rhs) :Cutsomer(rhs),priority(rhs.priority) { cout<<"PriorityCustomer Copy Ctor"<<endl; } PriorityCustomer& operator=(const PriorityCustomer& rhs) { cout<<"PriorityCustomer assign operator"<<endl; Cutsomer::operator=(rhs); priority=rhs.priority; return *this; }

Effective C++ 條款12