Re: [問題] 繼承關係下的 assignment overloading?
※ 引述《yawaog (^_^)》之銘言:
: 如果 base class 和 derived class 都有動態配置記憶體
: 那當一個 derived class 物件 assign 給另一個 derived
: class 物件時, 怎麼做比較好呢?
: 我寫了程式測了一下, 並不會自動呼叫 base class 的 operator= 耶,
: 不會是要在 derived class 的 operator= 一併處理吧
你答對了. XD
: Base& Base::operator=(const Base& b){
: delete pB;
: pB = new char[strlen(b.pB)+1];
: strcpy(pB,b.pB);
: return *this;
: }
=> the better way :
Base& Base::operator= ( const Base& b )
{
if( this != &b )
{
// here is your code.
}
return *this;
}
: Derived& Derived::operator=(const Derived& d){
: delete pD;
: pD = new char[strlen(d.pD)+1];
: strcpy(pD,d.pD);
: return *this;
: }
write like this :
Derived& Derived::operator=( const Derived& d )
{
if( this != &d )
{
// call operator = of Base class.
static_cast<Base&>(*this) = static_cast<const Base&>(d);
// here is your code.
// ...
}
return *this;
}
有錯請指教 :)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.116.246.54
※ 編輯: babyghost 來自: 140.116.246.54 (05/25 11:55)
推
05/25 12:40, , 1F
05/25 12:40, 1F
推
05/25 14:13, , 2F
05/25 14:13, 2F
推
05/25 14:28, , 3F
05/25 14:28, 3F
→
05/25 15:53, , 4F
05/25 15:53, 4F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章