exam4.cpp

来自「C++语言程序设计题典」· C++ 代码 · 共 86 行

CPP
86
字号
#include <iostream.h>
class Point
{
	int x,y;
public:
	Point() { x=y=0; }
	Point(int i,int j) { x=i;y=j; }
	Point(Point &);
	~Point() {}
	void offset(int,int);        //提供对点的偏移
	void offset(Point);          //重载,偏移量用Point类对象表示
	bool operator==(Point);      //运算符重载,判断两个对象是否相同
	bool operator!=(Point);      //运算符重载,判断两个对象是否不相同
	void operator+=(Point);      //运算符重载,将两个点对象相加
	void operator-=(Point);      //运算符重载,将两个点对象相减
    Point operator+ (Point);     //运算符重载,相加并将结果放在左操作数中
	Point operator- (Point);     //运算符重载,相减并将结果放在左操作数中
	int getx() { return x; }
	int gety() { return y; }
	void disp() 
	{
		cout << "(" << x << "," << y << ")" << endl;
	}
};
Point::Point(Point &p)
{
	x=p.x;y=p.y;
}
void Point::offset(int i,int j)
{
	x+=i;y+=j;
}
void Point::offset(Point p)
{
	x+=p.getx();y+=p.gety();
}
bool Point::operator==(Point p)
{
	if (x==p.getx() && y==p.gety())
		return 1;
	else
		return 0;
}
bool Point::operator!=(Point p)
{
	if (x!=p.getx() || y!=p.gety())
		return 1;
	else
		return 0;
}
void Point::operator+=(Point p)
{
	x+=p.getx();y+=p.gety();
}
void Point::operator-=(Point p)
{
	x-=p.getx();y-=p.gety();
}
Point Point::operator+(Point p)
{
    this->x+=p.x;this->y+=p.y;
	return *this;
}
Point Point::operator-(Point p)
{
    this->x-=p.x;this->y-=p.y;
	return *this;
}
void main()
{
	Point p1(2,3),p2(3,4),p3(p2);
	cout << "1:";p4.disp();
	p4.offset(10,10);
	cout << "2:";p4.disp();
	cout << "3:" << (p2==p3) << endl;
	cout << "4:" << (p2!=p3) << endl;
	p3+=p1;
	cout << "5:";p4.disp();
	p3-=p2;
	cout << "6:";p4.disp();
    p3=p1+p3;    //先将p1+p3的结果放在p1中,然后赋给p3,所以p1=p3
	cout << "7:";p4.disp();
    p3=p1-p2;
	cout << "8:";p4.disp();
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?