Effective c++学习笔记——条款10:令operator=返回一个*this的引用

本文深入探讨了C++中赋值操作符返回*this的协议及其背后的原因,通过实例展示了如何实现连锁赋值,并强调了遵循此协议对于类设计的必要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Have assignment operators return a reference to *this
从题目,我们就要记住这条信息,让你的operator=函数return *this;
基本类型int、char等都提供了连锁赋值,并采用右结合律。
int x, y, z;
x = y = z = 15; 这句真正被解析为:x = (y = (z = 15));
为了实现连锁赋值,赋值操作符必须返回一个引用指向操作符左侧实参,这是通常在C++中为classes所遵循的协议。
下面看一个实际例子;
// have_assi.cpp : 定义控制台应用程序的入口点。 //2011/9/10 by wallwind on sunrise #include "stdafx.h" #include <iostream> using namespace std; class Widget { public: Widget():i(0){} Widget(int ii):i(ii){} Widget& operator=(const Widget &rhs) { this->setValue(rhs.getValue()); return *this; } Widget& operator+=(const Widget& rhs) { this->setValue(rhs.getValue() + this->getValue()); return *this; } int getValue() const {return i;} void setValue(int ii){i=ii;} private: int i; }; int _tmain(int argc, _TCHAR* argv[]) { Widget w1,w2,w3; w1=w2=w3=10; cout<<w1.getValue()<<endl; cout<<w2.getValue()<<endl; cout<<w3.getValue()<<endl; w1+=10; w2+=20; w3+=30; cout<<w1.getValue()<<endl; cout<<w2.getValue()<<endl; cout<<w3.getValue()<<endl; return 0; }
输出结果,如图所示
如书中所说,这只是个协议,并我强制性,如果不遵守,代码一样可以通过他编译。然而c++的内置类型,和stl如
string vector 等都遵守这个协议。所以,你最好按这个做吧。

请记住:

令赋值(assignment)操作符返回一个reference to *this。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值