运算符++的返回值

Sla*_*zer 11 c++

我有以下代码被破坏.我可以通过修改代码中的某些行来修复它(请参阅注释).问题的原因是什么?

#include <iostream>
using namespace std;

class Number{
public:
    int n;
    Number(int a):n(a){}

    //when I change the following to
    //friend Number& operator++(Number& source, int i)
    //then it compiles fine and correct value is printed
    friend Number operator++(Number& source, int i){
        ++source.n;
        return source;
    }
};

int main() {

    Number x(5);
    x++++; //error: no 'operator++(int)' declared for postfix '++' [-fpermissive]
    cout<<x.n;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 16

您尝试将第二个++应用于第一次调用返回的临时对象.但是,操作数必须通过引用传递,并且您不能将临时绑定到非常量左值引用.

你可能不想"修复"这个,因为没有理由修改这样的临时值.但是,您应该递增之前返回值的副本,以提供预期的增量后行为.

前缀运算符应返回一个引用,该引用可以愉快地绑定到另一个引用,以便++++x;应该按预期工作.

  • @NikBougalis:让它成为非成员的一个很好的理由是,如果你写'x ++++;',你会得到一个错误而不是意想不到的结果,如问题所示. (2认同)

小智 8

您正在operator++通过写入递增内部的返回值x++ ++.这意味着如果该运算符的返回值不是可修改的值,则代码将无法编译.

因此,如果你声明它返回Number而不是Number &,则它不能被修改(函数的返回值是临时的而不是左值,除非它是引用,因此外部运算符++,它接受它(非const)引用,不能将它绑定到value返回的对象).