这一篇博客记录我学习Effective C++ term10的学习笔记!

Effective C++ term10 教会我:

        在类中重载赋值运算符(比如operator=)时,应该令operator=返回一个reference to *this 的形式。

(即在重载这些赋值运算符时,返回值要用reference to *this的形式返回,也即用类名&做返回值)

下面就是用标准的代码规范写的代码:

#include<iostream>
using std::cout;
using std::cin;
using std::endl;

class Widget
{
public:
	int m_wid;
public:
	Widget(){}
	Widget(int wid):m_wid(wid){}
	//规范的!
	Widget& operator=(const Widget& widt)
	{
		this->m_wid = widt.m_wid;
		return *this;//指向当前的对象 并且返回值类型是Widget类的一个对象
	}
	//当然,所有的赋值相关的运算都适用这一套东西

	//规范的!
	Widget& operator+=(const  Widget& widt)
	{
		this->m_wid = widt.m_wid;
		return *this;//这个term协议适用于 += -= *= /= 等等操作
	}
	Widget& operator=(int rhs)
	{
		//...
		return *this;//这函数也适用 但就是这个操作符的参数类型不符合协定 必须是const 类名& 对象名 才行,才是一个合格的安全的赋值参数语句

	}
};
int main(void)
{
	Widget w1(120), w2, w3;
	w3 = w2 = w1;//把w1赋值给w2,把w2更新后的这份对象值赋值给w3
	cout << "w1.m_wid = " << w1.m_wid << endl;
	cout << "w2.m_wid = " << w2.m_wid << endl;
	cout << "w3.m_wid = " << w3.m_wid << endl;
	system("pause");
	return 0;
}

运行结果:

 

 

 

参考:

Effective C++ 之条款10

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐