首页 > 代码库 > Effective C++ 条款12

Effective C++ 条款12

复制对象时,勿忘其每个成分

作者在本节条款提醒我们,在多重继承的情况下进行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;
    }
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

Effective C++ 条款12