问题(Question):
class ADD{
friend ADD operator++(ADD op);
friend ADD operator++(ADD &op,int n);
public: ADD(int i=0,int j=0) {a=i;b=j;}
void show() const{cout << "a=" << a << ",b=" << b << endl;}
private:
int a,b; };
ADD operator++(ADD op)
{ ++op.a;
++op.b;
cout << "++1 \r\n";
return op;}
ADD operator++(ADD &op,int n){
++op.a;
++op.b;
cout << "++2 \r\n";
return op;}
int main(int argc, char **argv)
{
ADD obj(1,2);
obj.show();
(obj++).show();
obj.show();
(++obj).show();
obj.show();
}
喂入的资料(Input):
预期的正确结果(Expected Output):
a=1,b=2
a=2,b=3
a=2,b=3
a=3,b=4
a=2,b=3
错误结果(Wrong Output):
程式码(Code):(请善用置底文网页, 记得排版)
补充说明(Supplement):
关键在于 (obj++).show(); 会呼叫ADD operator++(ADD &op,int n)
(++obj).show() 呼叫 ADD operator++(ADD op)
为什么哩?
网络上查的资料
class Object {
//...
public:
Object operator++();
Object operator++(int);
} obj;
//...
++obj; //is equivalent to
obj.operator++();
obj++; //is equivalent to
obj.operator++(0);