9、对Point类重载++和――运算符 编写C++程序完成以下功能: (1) Point类的属性包括点的坐标(x,y); (2) 实现 Point类重载++和――运算符: l ++p,--p,p++,p--。 l ++和――分别表示x,y增加或减少1。 #include<iostream> 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<<"("<<x<<","<<y<<")"; } int main() { Point a,b; float m,n; cout<<"请输入一个点坐标:"<<endl; cin>>m>>n; a.SetPoint(m,n); cout<<"输入点坐标为:"<<endl; a.output(); cout<<endl<<endl; b=(a++); a.output(); cout<<"++"; cout<<"="; b.output(); cout<<endl<<endl; b=(a--); a.output(); cout<<"--"; cout<<"="; b.output(); cout<<endl<<endl; b=(++a); cout<<"++"; a.output(); cout<<"="; b.output(); cout<<endl<<endl; b=(--a); cout<<"--"; a.output(); cout<<"="; b.output(); cout<<endl<<endl; system("pause"); return 0; }
|
|
来自: BUPT-BYR > 《cpp语言实例交流》