zoukankan      html  css  js  c++  java
  • c++ 拷贝构造函数 继承

    拷贝构造函数要求把所有变量都需要做拷贝。在有继承关系情况先,子类的拷贝构造函数,需要调用父类拷贝构造函数。示例代码如下:

    class Base{
    public:
        virtual ~Base();
        Base(const char *pStr);
        Base(const Base &other);
        virtual void CallFunction() ;
    public:
        char *m_pBase;
    };
    
    Base::Base(const char *pStr){
        if (pStr) {
            long iLen = strlen(pStr)+1;
            m_pBase = new char[iLen];
            memset(m_pBase, 0, iLen);
            strcpy(m_pBase, pStr);
        }}
    
    Base::~Base(){
        if (m_pBase) {
            delete [] m_pBase;
            m_pBase = NULL;
        }
    }
    
    Base::Base(const Base &other){
        if (m_pBase) {
            delete m_pBase;
            m_pBase = NULL;
        }
        long iLen = strlen(other.m_pBase)+1;
        m_pBase = new char[iLen];
        memset(m_pBase, 0, iLen);
        strcpy(m_pBase, other.m_pBase);
    }
    class Child:public Base{
    public:
        ~Child();
        Child(const char *pStr , const char *pBase);
        Child(const Child &other);
    public:
        char *m_pChild;
    };
    
    Child::Child(const char *pStr , const char *pBase):Base(pBase){//初始化列表中调父类构造函数
        if (pStr) {
            long iLen = strlen(pStr)+1;
            m_pChild = new char[iLen];
            memset(m_pChild, 0, iLen);
            strcpy(m_pChild, pStr);
        }
    }
    
    Child::Child(const Child &other):Base(other){//调父类拷贝构造函数
        if (m_pChild) {
            delete m_pChild;
            m_pChild = NULL;
        }
        long iLen = strlen(other.m_pChild)+1;
        m_pChild = new char[iLen];
        memset(m_pChild, 0, iLen);
        strcpy(m_pChild, other.m_pChild);
    }
    
    
    Child::~Child(){
        if (m_pChild) {
            delete [] m_pChild;
            m_pChild = NULL;
        }
    }

    Test:

    Child ch("child", "base");

     Child ch2(ch);

      

  • 相关阅读:
    字符串套餐(更新中)
    洛谷P4145 上帝造题的七分钟2 / 花神游历各国(重题:洛谷SP2713 GSS4
    [AHOI2013]作业
    我的配置
    [HAOI2006]受欢迎的牛
    洛谷P1456Monkey King
    洛谷P2331[SCOI2005]最大子矩阵
    如何更换博客背景
    洛谷P2419 [USACO08JAN]牛大赛Cow Contest
    JS正则表达式验证数字
  • 原文地址:https://www.cnblogs.com/zhidao-chen/p/3831320.html
Copyright © 2011-2022 走看看