Why does overloaded assignment operator return reference to class?

后端 未结 3 418
一生所求
一生所求 2021-01-18 17:40
class item {
public:
    item& operator=(const item &rh) {
        ...
        ...
        return *this;
    }
};

Is the following signatur

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-18 18:06

    It's perfectly legal. But when you declare operator= like that, you will be unable to make "chain of assignment":

    item a(X);
    item b;
    item c;
    c = b = a;
    

    Reference allows modifying returned value. Since operator= is evaluated from right to left, the usage I showed to you is working.

    EDIT Also, as others mentioned, return value is often used in expressions like while (a = cin.get()) != 'q'). But you also can declare operator like A operator=(const A&) (returns copy) or const A& operator(const A&) (returns const reference). My point is: this operator can return anything, but the idiomatic way is to return non-const reference to itself.

提交回复
热议问题