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函数。

  • 相关阅读:
    事件
    10- JMeter5.1.1 工具快速入门
    06- Linux Ubuntu下sublime下载与使用与安装包
    控件是什么意思?
    09- 性能测试关键指标
    08- Tomcat入门与环境搭建部署
    07- HTTP协议详解及Fiddler抓包
    06- web兼容性测试与web兼容性测试工具
    05- web网站链接测试与XENU工具使用
    04- cookie与缓存技术
  • 原文地址:https://www.cnblogs.com/kane0526/p/3611881.html
Copyright © 2011-2022 走看看