zoukankan      html  css  js  c++  java
  • C++复制对象时勿忘每一部分

    现看这样一个程序:

    void logCall(const string&  funcname) //标记记录
    {
        cout <<funcname <<endl;
    }
    
    class Custom
    {
        public:
        Custom(const Custom& p):name(p.name)
        {
            logCall("Custom copy constructor!")
        }
        Custom& operator=(const Custom& p)
        {
            logCall("Custom copy assignment operator!")
            name=p.name;
            return *this;
        }
        private :
            string  name;
    };
    
    class PriorityCustom:public Custom   //派生类
    {
        public:
        PriorityCustom(const PriorityCustom& p):priority(p.priority)
        {
            logCall("PriorityCustom copy constructor!")
        }
        PriorityCustom& operator=(const PriorityCustom& p)
        {
            logCall("PriorityCustom copy assignment operator!")
            priority=p.priority;
            return *this;
        }
        private :
            string  priority;
    };

    这样一看,藐视程序该做的赋值工作都做了,PriorityCustom的copy函数好像把要复制的工作都做了。

    错!请再看一眼。

    这样复制的话就有派生类的内容被复制了,而基类的内容却没有复制过去。因为这个复制过程没有调用过基类的copy函数,这样做的话复制完基类内容将是初始化状态。

    怎么做呢?派生类复制过程确保基类copy函数也被调用。

    class PriorityCustom:public Custom   //派生类
    {
        public:
        PriorityCustom(const PriorityCustom& p):Custom(p),priority(p.priority)
        {
            logCall("PriorityCustom copy constructor!")
        }
        PriorityCustom& operator=(const PriorityCustom& p)
        {
            logCall("PriorityCustom copy assignment operator!")
            Custom::operator=(p);
            priority=p.priority;
            return *this;
        }
        private :
            string  priority;
    };

    注意:

    当你写一个copying函数,请确保:

    1、复制所有local成员变量。

    2、调用所有基类内的适当copying函数。

  • 相关阅读:
    MongoDB —— 第三篇 高级操作
    MongoDB —— 第七篇 运维技术
    MongoDB —— 第八篇 驱动实践
    EditPlus 使用技巧集萃(转)
    面试经验网上资源汇总
    设计模式网上资料整合理解——创建型模式(一)
    C#编写扩展存储过程
    利用VS调试脚本
    用DevExpress.XtraReports实现复杂报表套打的一些经验
    无废话.NET帮助文件生成——Sandcastle+SHFB
  • 原文地址:https://www.cnblogs.com/kane0526/p/3611881.html
Copyright © 2011-2022 走看看