• 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;
        }
  • 相关阅读:
    JVM—Java内存结构
    myeclipse中页面utf-8的设置
    Python-统计txt文件里面的分数
    Python-字符串常用函数
    初识C#扩展方法
    Artwork 18年中南多校第一场A
    HDU2586 How far away ?
    HDU5952 Counting Cliques 暴搜优化
    POJ 2763 Housewife Wind 树链拋分
    HDU 3966 Aragorn's Story 树链拋分
  • 原文地址:https://www.cnblogs.com/jhcelue/p/7053749.html
Copyright © 2020-2023  润新知