問題(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);