重写子类中的赋值操作符

class   Base   { 
public: 
Base(int   initialValue   =   0):   x(initialValue)   {} 
private: 
int   x; 

class   Derived:   public   Base   { 
public: 
Derived(int   initialValue) 
:   Base(initialValue),   y(initialValue)   {} 
Derived&   operator=(const   Derived&   rhs); 
private: 
int   y; 
}; 

Derived&   Derived::operator=(const   Derived&   rhs) 

if   (this   ==   &rhs)   return   *this; 
Base::operator=(rhs);   //   调用this-> Base::operator= 
y   =   rhs.y; 
return   *this;

}

 

这里只是显式地调用了Base::operator=,这个调用和一般情况下的在成员 
函数中调用另外的成员函数一样,以*this   作为它的隐式左值。Base::operator= 
将针对*this   的Base   部分执行它所有该做的工作——正如你所想得到的那种效 
果。 
但如果基类赋值运算符是编译器生成的,有些编译器会拒绝这种对于基类 
赋值运算符的调用(见条款45)。为了适应这种编译器,必须这样实现 
Derived::operator=: 
Derived&   Derived::operator=(const   Derived&   rhs) 

if   (this   ==   &rhs)   return   *this; 
static_cast <Base&> (*this)   =   rhs;   //   对*this   的Base   部分 
//   调用operator= 
y   =   rhs.y; 
return   *this; 

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值