我有下面的代码被破坏。我可以通过修改代码中的某一行来修复它(请参阅评论)。问题的原因是什么?运算符的返回值++
#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;
}
这为什么让你感到惊讶?想想postfix'operator ++'的语义,你回来了什么,你正在尝试做什么以及你想要为谁做什么。 –
为什么你的代码中需要'friend'? – triclosan
@triclosan在这里没有必要,但假设他有一个私人成员,并且想要一个全局函数而不是成员超载? –