先奉上代码:
#include <iostream.h>
class Point
{
public:
int x,y;
Point(){x=y=0;}
Point(int i,int j){x=i;y=j;}
Point(Point &);
~Point(){}
void offset(int,int); //提供对点的偏移
void offset(Point &a); //重载,偏移量用Point类对象表示
bool operator ==(Point &a); //运算符重载,判断两个对象是否相同
bool operator !=(Point &a); //运算符重载,判断两个对象是否不相同
void operator +=(Point &a); //运算符重载,将两个点对象相加
void operator -=(Point &a); //运算符重载,将两个点对象相减
Point operator +(Point &a); //运算符重载,相加并将结果放在左操作数中
Point operator -(Point &a); //运算符重载,相减并将结果放在左操作数中
int getx(){return x;}
int gety(){return y;}
void display();
};
void Point::offset(int a,int b)
{
x=x+a;
y=y+b;
}
void Point::offset(Point &a)
{ x=x+a.x;
y=y+a.y;
}
bool Point::operator==(Point &a)
{
if( getx()==a.getx()&&gety()==a.gety())
return true;
else
return false;
}
bool Point::operator!=(Point &a)
{
if( getx()==a.getx()&&gety()==a.gety())
return false;
else
return true;
}
void Point::operator +=(Point &a)
{
x=x+a.x;
y=y+a.y;
}
void Point::operator -=(Point &a)
{
x=x-a.x;
y=y-a.y;
}
Point Point::operator +(Point &a)
{
x=x+a.x;
y=y+a.y;
return Point(x,y);
}
Point Point::operator -(Point &a)
{
x=x-a.x;
y=y-a.y;
return Point(x,y);
}
void Point::display()
{ cout<<"("<<x<<","<<y<<")"<<endl;
}
int main()
{ Point a(3,6),b(7,9),c;
cout<<"please input the x and y of point";
cin>>a.x>>a.y;
int m,n;
m=a==b;
if(m==1)
cout<<"a==b";
else
cout<<"a!=b"<<endl;
a.offset(5,6);
a.display();
a.offset(b);
a.display();
a+=b;
a.display();
a-=b;
a.display();
c=a+b;
c.display();
c=a-b;
c.display();
return 0;
}
最近学习了重载,写了个代码。不是很好,请大家批评指正。重载我感觉很好玩,以后有时间再写一下。睡觉去啦!!!!!!!!!!!!!!11