c++派生类赋值操作符
C++ derived class assignment operator
我正在阅读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!
相关文章:
- 赋值给派生类的基组件
- C++ - 从基类"inherit"重载赋值运算符派生类的安全/标准方法
- c++中的重载赋值操作符
- c++类继承和赋值操作符
- 带引用类成员的赋值操作符
- 复制构造函数,赋值操作符重载
- c++派生类赋值操作符
- 通过调用Move赋值操作符实现Move构造函数
- 带有映射的赋值操作符
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 用于具有const数据成员的类的move和右值赋值操作符
- 类赋值操作符和复制构造函数
- 赋值操作符重载
- 影响正确性的move构造函数/赋值操作符示例
- 当类是子类时重载赋值操作符
- 如果没有定义Move语义(Move构造函数和Move赋值操作符),编译器是否默认优化
- 带有派生类型参数的赋值操作符
- 移动QWidget派生的赋值操作符