C++继承细节 -2

  • 继承与动态内存分配
//基类定义
class BaseClass {
   private:
        char *label;
   public:
        BaseClass() {}
        BaseClass(const char *l);
        virtual ~BaseClass();
        BaseClass(const BaseClass &bc);
        BaseClass &operator=(const BaseClass &bc);
};
BaseClass::BaseClass(const BaseClass &bc)
{
    this->label = new char[std::strlen(bc.label)+1];
    std::strcpy(this->label, bc.label);
}
BaseClass &BaseClass::operator=(const BaseClass &bc)
{
    this->label = new char[std::strlen(bc.label)+1];
    std::strcpy(this->label, bc.label);
}
BaseClass::~BaseClass()
{
    delete[] this->label;
}
1. 派生类中的数据成员没用`new`分配内存,则不需要为派生类提供 *复制构造函数*、*赋值运算符*;因为在使用已知对象对另一个对象初始化时派生类的默认复制函数将调用基类的显示复制函数(BaseClass(const BaseClass &bc))进行深拷贝,同理赋值运算符也一样。
//派生类定义
class DerivedClass : public BaseClass {
private:
        char style[20]; //使用栈空间
public:
        DerivedClass() {}
        DerivedClass(const char *st);
};
2. 派生类中的数据成员使用`new`分配内存,则派生类需要提供 *复制构造函数*、 *赋值运算符*,具体实现如下:
//派生类
class DerivedClass : public BaseClass {
private:
        char *style;
public:
        DerivedClass() {}
        DerivedClass(const char *st);
        ~DerivedClass() {delete[] this->style;}
        DerivedClass(const DerivedClass &dc);
        DerivedClass &operator=(const DerivedClas &dc);
};
//显示复制构造函数
DerivedClass::DerivedClass(const DerivedClass &dc) : BaseClass(dc)
{
    this->style = new char[std::strlen(dc.style)+1];
    std::strcpy(this->style, dc.style);
}
//赋值运算符
DerivedClass & DerivedClass::operator=(const DerivedClass &dc)
{
    if (this == &dc) {
        return *this;
    }
    delete[] this->style;
    //注意,注意,注意
    BaseClass::operator=(dc); //显示调用基类赋值运算符函数
    this->style = new char[std::strlen(dc.style)+1];
    std::strcpy(this->style, dc.style);
    return *this;
}

转载于:https://www.cnblogs.com/Focus-Flying/p/9101508.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值