c++ point类(含输入和输出的重载)

【问题描述】

定义类point,其中包括两个数据成员,均为 int 类型,为点的横坐标和纵坐标。

类的成员函数如下:

构造函数:包括两个参数,其两个参数的默认值为0。

重载运算符 +、- 、 ==、 != 

+:两个点相应的坐标相加,比如(1,1)+(2,2)=(3,3)

 -:两个点相应的坐标相减,比如(2,2)-(1,1)=(1,1)

== :两个点相应坐标如果相等,则结果为true,否则结果为false

!= :两个点的两个坐标只要有一个不相等,则结果为true,否则结果为false

非成员函数:

重载运算符<<,输出点的横坐标和纵坐标,如(2,3)其中2为横坐标,3为纵坐标

重载运算符>>,输入点的横坐标和纵坐标,中间以空格隔开比如输入2 3 ,给点的横坐标和纵坐标赋值.

注意:输入/输出流运算符重载不能使用友元函数 

其主函数如下:

int main()
{
         point  x, y, z1, z2;
         cin>>x>>y;
          z1=x+y;
         z2=x-y;
        cout<<z1<<z2;

         if(x==y)   cout<<"x==y"<<endl;
         else   cout<<"x!=y"<<endl;

         if(z1!=z2)   cout<<"z1!=z2"<<endl;
         else   cout<<"z1==z2"<<endl;
         return 0;
}
【输入形式】输入有2行,每行输入一个点的横坐标和纵坐标, 中间用空格隔开

【输出形式】输出有4行,第1行输出 x,y 两点之和,即z1; 第2行输出x,y 两点之差,即z2;

第3行输出 x, y 两点的比较结果, 如果两点相等, 则输出"x==y", 否则输出"x!=y";

第4行输出 z1, z2 两点的比较结果, 如果两点不相等, 则输出"z1!=z2", 否则输出"z1==z2";
【样例输入】

3 4

1 2
【样例输出】

(4,6)

(2,2)

x!=y

z1!=z2

 

AC代码

#include<iostream>
using namespace std;
class point
{
public:
	point(int a = 0, int b = 0)
	{
		x = a;
		y = b;
	}
	void get(int &m, int &n)
	{
		m = x;
		n = y;
	}
	void set(int m, int n)
	{
		x = m;
		y = n;
	}
	point operator+(point p);
	point operator-(point p);
	bool operator == (point p);
	bool operator != (point p);
private:
	int x;
	int y;
};

point point::operator+(point p)
{
	point temp;
	temp.x = this->x + p.x;
	temp.y = this->y + p.y;
	return temp;
}

point point::operator-(point p)
{
	point temp;
	temp.x = this->x - p.x;
	temp.y = this->y - p.y;
	return temp;
}

bool point::operator==(point p)
{
	return (this->x == p.x) && (this->y == p.y);
}

bool point::operator!=(point p)
{
	return (this->x != p.x) || (this->y != p.y);
}

ostream& operator<<(ostream &os, point &p)
{
	int m, n;
	p.get(m, n);
	os << "(" << m << "," << n << ")" << endl;
	return os;
}

istream& operator>>(istream &is, point &p)
{
	int m, n;
	is >> m;
	is.ignore(1);//忽略空格
	is >> n;
	is.ignore(1);//忽略回车
	p.set(m, n);
	return is;
}

int main()
{
	point  x, y, z1, z2;
	cin >> x >> y;
	z1 = x + y;
	z2 = x - y;
	cout << z1 << z2;

	if (x == y)   cout << "x==y" << endl;
	else   cout << "x!=y" << endl;

	if (z1 != z2)   cout << "z1!=z2" << endl;
	else   cout << "z1==z2" << endl;
	return 0;
}
  • 6
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值