有人可以向我解释为什么我的重载++(预版本)没有更新值吗?片段是这样的:
circle circle:: operator++()
{
Area = Area * 2.0;
return *this;
}
/////////////////////////////
int main()
{
class circle c1(4, 1, -1), c2(12, 4, 6);
c1.output();
c1++;
c1.output();
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是因为你重载前缀并调用后缀.你需要打电话++c1;.要使用c1++;你还需要重载postfix:
circle operator++ ( int );
Run Code Online (Sandbox Code Playgroud)
您的重载运算符的签名应该是:
circle& operator++(); // return by reference and this is prefix.
Run Code Online (Sandbox Code Playgroud)
但你使用postfix,所以它应该是:
circle operator++ (int); // int is unused
Run Code Online (Sandbox Code Playgroud)
更改签名是不够的,因为您实现了前缀逻辑,直接更改值而不保存初始值.因此,如果你在类似的组合表达式中使用postfix运算符(c++).output(),那么它就不会尊重预期的语义.
这里是两个版本的实现:
circle& operator++ () { // prefix
Area = Area * 2.0; // you can change directly the value
cout << "prefix"<<endl;
return *this; // and return the object which contains new value
}
circle operator++ (int) { // postfix
circle c(*this); // you must save current state
Area = Area * 2.0; // then you update the object
cout << "postfix"<<endl;
return c; // then you have to return the value before the operation
}
Run Code Online (Sandbox Code Playgroud)
这里有一个在线演示,以显示两者之间的差异.