作者babyghost (赚P币去赌博!!)
看板C_and_CPP
标题Re: [问题] 继承关系下的 assignment overloading?
时间Thu May 25 11:54:49 2006
※ 引述《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)
1F:推 cplusplus:ps. 视情况决定是否呼叫BASE的op= 05/25 12:40
2F:推 yawaog:太漂亮了,原来可以这样叫Base的op=,不知怎麽怪感动的,thx 05/25 14:13
3F:推 yawaog:资工系?, 和 246.50 同学? 05/25 14:28
4F:→ babyghost:XD 同 lab 吧 XD 05/25 15:53