Effective C++之 Item 10: 让 assignment operators(赋值运算符)返回一个 reference to *this(引向 *this 的引用)

关于 assignments(赋值)的一件有意思的事情是你可以把它们穿成一串。

int x, y, z;

x = y = z = 15;                        // chain of assignments

另一件有意思的事情是 assignment(赋值)是 right-associative(右结合)的,所以,上面的赋值串可以解析成这样:

x = (y = (z = 15));

这里,15 赋给 z,然后将这个 assignment(赋值)的结果(最新的 z)赋给 y,然后将这个 assignment(赋值)的结果(最新的 y)赋给 x。

这里的实现方法是让 assignment(赋值)返回一个 reference to its left-hand argument(引向它的左侧参数的引用),而且这就是当你为你的 classes(类)实现 assignment operators(赋值运算符)时应该遵守的惯例:

class Widget {
public:
  ...
Widget& operator=(const Widget& rhs)   // return type is a reference to
{                                      // the current class
  ...
  return *this;                        // return the left-hand object
  }
  ...
};

这个惯例适用于所有的 assignment operators(赋值运算符),而不仅仅是上面那样的标准形式。因此:

class Widget {
public:
  ...
  Widget& operator+=(const Widget& rhs   // the convention applies to
  {                                      // +=, -=, *=, etc.
   ...
   return *this;
  }
   Widget& operator=(int rhs)            // it applies even if the
   {                                     // operator's parameter type
      ...                                // is unconventional
      return *this;
   }
   ...
};

这仅仅是一个惯例,代码并不会按照这个意愿编译。然而,这个惯例被所有的 built-in types(内建类型)和标准库中(或者即将进入标准库——参见 Item 54)的 types(类型)(例如,string,vector,complex,tr1::shared_ptr 等)所遵守。除非你有好的做不同事情理由,否则,不要破坏它。

Things to Remember

  • 让 assignment operators(赋值运算符)返回一个 reference to *this(引向 *this 的引用)。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值