我正在阅读 C++ Primer 第 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中的删除标签)?
谢谢你。