条款 10:令 operator= 返回一个指向 *this 的引用

 赋值的一个有趣之处在于,可以将它们串在一起:

int x, y, z;
x = y = z = 15; // 将赋值运算串起来
                // x = (y = (z = 15));

实现这种操作的方式是,赋值操作返回一个指向左侧参数的引用。
自定义的类,实现赋值操作符时应该遵循这个约定:

#include <iostream>

class Widget {
public:
    Widget(int cnt):data(cnt){}
    Widget& operator=(const Widget& rhs) // 返回类型是当前类的一个引用
    {
        this->data = rhs.data;
       return *this; // 返回左值对象
    }
    Widget& operator++() // 这个约定也适用于+=, -=, *=等
    {
        this->data ++;
        return *this;
    }
    Widget& operator++(int a) // 这个约定也适用于+=, -=, *=等
    {
        this->data++;
        return *this;
    }
    Widget& operator+=(const Widget& rhs) // 这个约定也适用于+=, -=, *=等
    {
        this->data += rhs.data;
        return *this;
    }
    Widget& operator=(int rhs) // 即使参数的类型不符合约定,也适用
    {
       this->data = rhs;
       return *this;
    }

    int getData() { return data; }
private:
    int data;
};

int main()
{
    Widget a = Widget(1);
    Widget b = Widget(2);
    Widget c = Widget(5);

    ++((a = b += c = 10)++);
    std::cout << "a=" << a.getData() << "  b=" << b.getData() << "  c=" << c.getData() << std::endl;
}

在这里插入图片描述

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值