[英]C++ derived class assignment operator
我正在閱讀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中的delete標簽)?
謝謝。
到那時, style
已經從上次調用new char []設置了一個指針。 如果分配給它,您將失去最后一次調用delete []的機會,並造成內存泄漏。
重要的是,將您顯示的代碼視為概念的演示。 通常,您不應該直接執行此類操作,而要擁有專門負責任務的成員,並且外部類根本不需要dtor或op =。 就像您的示例一樣,標簽和樣式可以是std :: string,唯一需要手工繪制的dtor和op =是std :: string!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.