为什么重载的赋值运算符返回对类的引用? [英] Why does overloaded assignment operator return reference to class?

查看:56
本文介绍了为什么重载的赋值运算符返回对类的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class item {
public:
    item& operator=(const item &rh) {
        ...
        ...
        return *this;
    }
};

以下签名错误吗?

void operator=(const item &rh);

item a, b;
a = b; // equivalent to a.operator=(b); so there is no need to return this.

推荐答案

这不是错误",但令人惊讶.分配求值到目标对象.这就是内在的含义.如果您为自己的班级定义不同的名称,人们可能会感到困惑.

It is not "wrong", but surprising. An assignment evaluates to the target object. That's what the builtin meaning is. If you define it different for your own class, people could become confused.

示例:

int c;
while((c = getchar()) != EOF) {
  // ...
}

c 的赋值返回了 c 本身,然后将其与 EOF 进行了比较.用户希望您的 item 类的行为类似.

The assignment to c returned c itself and compared it to EOF afterwards. Users would expect your item class to behave similar.

这篇关于为什么重载的赋值运算符返回对类的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆