简体   繁体   中英

Why does overloaded assignment operator return reference to class?

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

Is the following signature wrong?

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.

Example:

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

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

The signature with void would not allow chained assignments:

a = b = c;

(Look at Johannes' answer for one more example of a usage pattern based on assignment returning the assigned value.)

That's why using such signatures is discouraged. However, if I am not mistaken, you actually can use such a signature.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM