美文网首页
[C++进阶]令operator= 返回一个reference

[C++进阶]令operator= 返回一个reference

作者: 小鱼号的代码日记 | 来源:发表于2020-09-06 23:00 被阅读0次

为了"连锁赋值",赋值操作符必须返回一个reference指向

操作符的左侧实参。

这是你为classes实现赋值操作符时应该遵循的协议。

/***************************
effectivre c++
改善编程与设计的55个具体做法
条款10:令operator= 返回一个reference to *this
 ---------小鱼号的代码日记--------------
****************************/
/*****
为了"连锁赋值",赋值操作符必须返回一个reference指向
操作符的左侧实参。
这是你为classes实现赋值操作符时应该遵循的协议。
*****/
class widget
{
public:
    widget& operator =(const widget& rhs)
    {
        return *this;
    }

    widget& operator +=(const widget& rhs)
    {
        return *this;
    }
};

#include <QCoreApplication>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    int x,y,z;
    x = y = z = 15;

    return a.exec();
}

内容选自:
effectivre c++
改善程序与设计的55个具体做法

相关文章

网友评论

      本文标题:[C++进阶]令operator= 返回一个reference

      本文链接:https://www.haomeiwen.com/subject/wpvhektx.html