【发布时间】:2013-07-31 01:33:28
【问题描述】:
我的以下代码已损坏。我可以通过修改代码中的某些行来修复它(参见注释)。问题的原因是什么?
#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;
}
【问题讨论】:
-
为什么这会让您感到惊讶?想一想后缀
operator++的语义,你要返回什么,你想做什么以及你想对谁做。 -
为什么你的代码中需要
friend? -
@triclosan 这里没有必要,但是假设他有一个私有成员并且想要一个全局函数而不是成员重载?
-
@triclosan 因为 operator++ 是一元的,如果它是一个成员函数,它将只有一个参数(int)。我相信这个有两个参数的版本不是成员函数(即使它是在类中定义的),因此需要这个朋友。
标签: c++