这道c++的运算符重载最后运行的答案是21,但是这是怎么算出来的呢??

来源:百度知道 编辑:UC知道 时间:2024/06/08 16:44:56
#include <iostream.h>
class I
{
public:
I(int x){value=x;}
I operator++();
I operator++(int);
void show()
{cout<<value<<endl;}
int value;
};
I I::operator ++()
{
value++;
return *this;
}
I I::operator ++(int)
{
I temp(*this);
value++;
return temp;
}
void main()
{I n(20);
++(++n);
n.show();
}

因为当函数是值返回状态的时候括号内的++n返回的不是n本身而是临时变量,用临时变量参与括号外的++运算,当然n的值也就只改变了一次。结果为21而不是22。
正确的方法是返回引用
I &I::operator ++()
{
value++;
return *this;
}

I& operator++(); //汗了,刚想起来