c++派生类赋值操作符

C++ derived class assignment operator

本文关键字:赋值操作符 派生 c++      更新时间:2023-10-16

我正在阅读c++入门第13章"类继承",关于派生类中的赋值操作符的一些内容使我感到困惑。情况是这样的:基类中:

class baseDMA
{
  private:
      char * label;// label will point to dynamic allocated space(use new)
      int rating;
  public:
      baseDMA & operator=(const baseDMA & rs);
      //remaining declaration...
};
//implementation
baseDMA & baseDMA::operator=(const baseDMA & rs)
{
      if(this == &rs)
      {
          return *this;
      }
      delete [] label;
      label = new char[std::strlen(rs.label) + 1];
      std::strcpy(label,rs.label);
      rating = rs.rating;
      return *this;
}
// remaining implementation

在派生类

class hasDMA : public baseDMA
{
    private:
        char * style;// additional pointer in derived class 
    public:
        hasDMA & operator=(const hasDMA& rs);
        //remaining declaration...
};
// implementation
hasDMA & hasDMA::operator=(const hasDMA & hs)
{
    if(this == &hs)
        return *this;
    baseDMA::operator=(hs);
    style = new char[std::strlen(hs.style) + 1];
    std::strcpy(style, hs.style);
    return *this;
}
// remaining implementation

我的问题是:在派生类赋值操作符定义中,为什么不需要在分配新空间之前先删除样式(如在baseDMA中删除标签)?

谢谢。

在这一点上,style有一个指针,你设置从以前的调用到新的char[]。如果你给它赋值,你就失去了最后一次调用delete[]的机会,并造成内存泄漏。

作为一个重要的注意事项,将您所展示的代码仅仅作为一个概念的演示。通常情况下,您不应该直接做这些事情,但是有一个专门负责任务的成员,外部类根本不需要doctor或op=。就像你的例子,标签和样式可以是std::string,唯一需要手工制作的dr和op=是std::string!