Effective C++ 条款16: 在operator=中对所有数据成员赋值

#include <iostream>

using namespace std;

class BaseA
{
public:
	int _i;	
	BaseA(int i): _i(i){};
	BaseA(const BaseA& rhs);
	BaseA& operator=(const BaseA& rhs);
};

BaseA::BaseA(const BaseA& rhs)
{
	_i = rhs._i;
}

BaseA& BaseA::operator=(const BaseA& rhs)
{
	if (&rhs == this)
	{
		return *this;
	}

	this->_i = rhs._i;
	return *this;
}

class DevA : public BaseA
{
public:
	int _j;
	DevA(int j):BaseA(j),_j(j){};
	DevA(const DevA& rhs);
	DevA& operator= (const DevA& rhs);
};

DevA::DevA(const DevA& rhs)
:BaseA(rhs._i)
{
	this->_j = rhs._j;
}

DevA& DevA::operator =(const DevA& rhs)
{
	if (&rhs == this)
	{
		return *this;
	}

	this->_j = rhs._j;
	return *this;
}

int main()
{
	DevA d(4);
	DevA d2(5);
	DevA d3(d);
	DevA d4 = d2;
	d = d2;

	return 0;
}
我们在定义自己的拷贝构造函数和赋值函数是一定要仔细,像上述例子中其实赋值函数它没有做到真正的赋值。在执行d = d2;后由于在DevA类中的赋值函数没有对BaseA中的_i变量进行复制所以早d中的_i和d2中的_i是不相等的。
要解决上述问题我们的修改下DevA中的赋值函数。
DevA& DevA::operator =(const DevA& rhs)
{
if (&rhs == this)
{
return *this;
}
static_cast<BaseA&>(*this) = rhs;


this->_j = rhs._j;
return *this;
}

只需改成上述一样即可。
在我们执行这样的语句时:DevA d3 = d;他的执行过程是先调用d3的拷贝构造函数在调用d3的赋值函数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值