don t stop the music:对Point类重载++和――运算符

来源:百度文库 编辑:中财网 时间:2024/04/29 11:35:00

 

9、对Point类重载++和――运算符

    编写C++程序完成以下功能:

(1)    Point类的属性包括点的坐标(x,y);

(2)    实现 Point类重载++和――运算符:

l        ++p,--p,p++,p--。

l        ++和――分别表示x,y增加或减少1。

 

#include

using namespace std;

 

class Point

{

private:

       float x;

       float y;

public:

       Point(float xx=0,float yy=0) {x=xx; y=yy;}

       void SetPoint(float xx=0,float yy=0) {x=xx; y=yy;}

       ~Point() {}

       void output();

    Point operator ++();

       Point operator --();

       Point operator ++(int);

       Point operator --(int);

 

};

 

Point Point::operator ++()

{

       Point b;

       b.x=x+1;

       b.y=y+1;

       return b;

}

 

Point Point::operator --()

{

       Point b;

       b.x=x-1;

       b.y=y-1;

       return b;

}

 

Point Point::operator ++(int)

{

       Point b;

       b.x=x+1;

       b.y=y+1;

       return b;

}

 

Point Point::operator --(int)

{

       Point b;

       b.x=x-1;

       b.y=y-1;

       return b;

}

 

 

 

void Point::output()

{

       cout<<"("<

}

 

int main()

{

       Point a,b;

       float m,n;

       cout<<"请输入一个点坐标:"<

       cin>>m>>n;

       a.SetPoint(m,n);

 

       cout<<"输入点坐标为:"<

       a.output();

       cout<

 

       b=(a++);

       a.output();

       cout<<"++";

       cout<<"=";

       b.output();

       cout<

 

       b=(a--);

       a.output();

       cout<<"--";

       cout<<"=";

       b.output();

       cout<

 

       b=(++a);

       cout<<"++";

       a.output();

       cout<<"=";

       b.output();

       cout<

 

       b=(--a);

       cout<<"--";

       a.output();

       cout<<"=";

       b.output();

       cout<

 

       system("pause");

       return 0;

}