C++类继承下的赋值运算符

来源:互联网 发布:双色球246包中6红矩阵 编辑:程序博客网 时间:2024/06/18 07:16
class Base {public:Base& operator=(const Base& rhy);Base(int val=0);private:int value;};//编译器禁止声明和定义时同时定义缺省参数值。//若声明时没有定义缺省参数值,那么在定义成员函数时可以定义缺省参数值。但这种情况通常用户是看不见的,因此应避免。Base::Base(int val) {value=val;}Base& Base::operator=(const Base& rhy) {if(this==&rhy) return *this;value=rhy.value;return *this;}class Derived:public Base {public:Derived(int val1,int val2);Derived& operator=(const Derived& rhy);private:int value2;};Derived& Derived::operator=(const Derived& rhy){if(this==&rhy) return *this;value2=rhy.value2;return *this;}

这样重载赋值操作符是错误的,因为它并没有对Derived的基类Base部分的成员value进行赋值。


方法二:可以使用基类的operator=函数对基类部分进行赋值:

Derived& Derived::operator=(const Derived& rhy) {if(this==&rhy) return *this;Base::operator=(rhy);value2=rhy.value2;return *this;}
这样定义一般情况下没错,但如果基类的赋值运算符是编译器自己合成的,那么有的编译器会拒绝这种对基类赋值运算符的调用。


方法三:

Derived& Derived::operator=(const Derived& rhy){if(this==&rhy) return *this;static_cast<Base&>(*this)=rhy;this->value2=rhy.value2;return *this; } 
将*this强制转化为Base&类型,调用基类的赋值运算符,只对基类Base部分进行赋值 ,注意这里必须转换成引用类型Base&,如果转成Base会调用拷贝构造函数创建新的对象,新对象成为赋值目标,而*this的成员保持不变,没有达到预期。


0 0