C++重载自增运算符(很容易搞混)
#include <iostream.h>
class CPoint
{
private:
int x,y;
public:
CPoint(int xx=0, int yy=0)
{
x = xx;
y = yy;
}
void disp()
{
cout<<"("<<x<<','<<y<<")"<<endl;
}
CPoint operator + (CPoint q)
{
return CPoint(x+q.x,y+q.y);
}
CPoint operator - (CPoint q)
{
return CPoint(x-q.x,y-q.y);
}
CPoint operator ++() //++CPoint
{
x++;
y++;
cout<<"++() called"<<endl;
return *this;
}
CPoint operator ++(int) //CPoint++
{
CPoint t(x,y);
x++;
y++;
cout<<"++(int) called"<<endl;
return t;
}
};
void main()
{
CPoint a(10,10), b;
a.disp();
b = a++; // call ++(int)
a.disp();
b.disp();
b = ++a; // call ++()
a.disp();
b.disp();
}
本文使用Blog_Backup未注册版本导出,请到soft.pt42.com注册。

浙公网安备 33010602011771号