題目
定義Point類,有座標_x,_y兩個成員變量;對Point類重載“++”(自增)、“–”(自減)運算符,實現對座標值的改變。
C++代碼如下:
#include<iostream>
using namespace std;
class Point
{
private:
int x,y;
public:
Point(int a,int b){x=a,y=b;}
Point& operator++();
Point operator++(int);
Point& operator--();
Point operator--(int);
void showPoint();
};
Point & Point::operator++()//前置++
{
++x,++y;
return *this;
}
Point Point::operator++(int)//後置++
{
x++,y++;
return *this;
}
Point & Point::operator--()//前置--
{
--x,--y;
return *this;
}
Point Point::operator--(int)//後置--
{
x--,y--;
return *this;
}
void Point::showPoint()
{
cout<<"x="<<x<<" y="<<y<<endl;
}
int main()
{
Point p(2,3);
p.showPoint();
cout << "前置++:";
++p;
p.showPoint();
cout << "後置++:" ;
p++;
p.showPoint();
cout << "前置--:" ;
--p;
p.showPoint();
cout << "後置--:" ;
p--;
p.showPoint();
return 0;
}