Why does overloaded assignment operator return reference to class?

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

Is the following signatur

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 18:04

    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.

提交回复
热议问题