Effective C++ 条款10解读: 令operator= 返回一个reference to *this

       我们先来看一个简单测程序:

 

#include <iostream>
using namespace std;

class A
{
private:
	int x;

public:
	A()
	{
	}

	A(int xx)
	{
		x = xx;
	}

	int get() const
	{
		return x;
	}

	void operator=(const A &a)
	{
		x = a.x;
	}
};

int main()
{
	A a, b, c(1);

	// ok
	b = c;
	a = b;
	cout << a.get() << endl;
	cout << b.get() << endl;
	cout << c.get() << endl;

	// error, 没法支持连续赋值
	a = b = c;
	cout << a.get() << endl;
	cout << b.get() << endl;
	cout << c.get() << endl;

	return 0;
}

       上面程序最大的问题在于不支持连续链式赋值, 更更改为:

 

 

#include <iostream>
using namespace std;

class A
{
private:
	int x;

public:
	A()
	{
	}

	A(int xx)
	{
		x = xx;
	}

	int get() const
	{
		return x;
	}

	A operator=(const A &a) // ok, but not perfect
	{
		x = a.x;
		return *this;
	}
};

int main()
{
	A a, b, c(1);

	// ok
	a = b = c;
	cout << a.get() << endl;
	cout << b.get() << endl;
	cout << c.get() << endl;

	return 0;
}

      结果为:

 

1
1
1

     虽然结果正确, 但是, 在返回的时候, 会有对象的拷贝, 有额外的消耗, 所以最好返回引用, 如下:

 

#include <iostream>
using namespace std;

class A
{
private:
	int x;

public:
	A()
	{
	}

	A(int xx)
	{
		x = xx;
	}

	int get() const
	{
		return x;
	}

	A& operator=(const A &a) // perfect
	{
		x = a.x;
		return *this;
	}
};

int main()
{
	A a, b, c(1);

	// ok
	a = b = c;
	cout << a.get() << endl;
	cout << b.get() << endl;
	cout << c.get() << endl;

	return 0;
}

      程序的结果为:

 

1
1
1

      实际上, C++的很多内置类型和STL库都是这样的。 其实, 除了operator=之外, operator+=也类似。比如:

 

#include <iostream>
using namespace std;

class A
{
private:
	int x;

public:
	A()
	{
	}

	A(int xx)
	{
		x = xx;
	}

	int get() const
	{
		return x;
	}

	A& operator+=(const A &a) // perfect
	{
		x += a.x;
		return *this;
	}
};

int main()
{
	A a(1), b(1), c(1);

	// ok
	a += b += c;
	cout << a.get() << endl;
	cout << b.get() << endl;
	cout << c.get() << endl;

	return 0;
}

      结果如下:

 

3
2
1

      好吧, 本文就先学习到这里了, 最后再次看一眼:Effective C++ 条款10: 令operator= 返回一个reference to *this.  

 

      哦, 对了, 差点忘记说:上述的opertor=函数其实不够perfect, 还有隐患, 需要处理“自我赋值”, 我们将会在后续博文中考虑这一点。
 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值