C++类继承下的赋值运算符
2016-01-20 15:16
232 查看
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的成员保持不变,没有达到预期。
相关文章推荐
- C语言中exit(0)与exit(1)有什么区别
- C++ template —— 深入模板基础(二)
- Visual C++ : H, Lib, DLL配置!
- C++(一)
- C++ Primer Plus(第六版)读书笔记(二)
- 求次方和
- C++中placement new操作符(经典)
- 从一简单程序看C语言内存分配
- C++的精髓——虚函数
- 用C++创建属于自己的类库?
- 脑上用VS2010编写的VC++程序(使用MFC库
- AndroidStudio 编译C/C++文件生成SO文件
- C#调用C++dll文件 运行提示找不到函数的入口点
- C++封装、继承、多态
- C++函数重定义、重载、重写
- VS2015 C#调试C++ dll时提示:“当前不会命中断点,因为还没有为该文档加载任何符号”解决方法From Eric Qu
- c++中struct使用注意事项
- <设计模式>系列汇总 By python and C++
- C语言实现龙贝格求积
- OJ上 G++ 与 C++ 的区别