C++实验05(01)Point类运算符重载

题目描述
声明Point类,有坐标x,y,为整型的私有数据成员。
声明成员函数:
Point& operator++();
Point& operator+(Point);
Point(int x = 0,int y =0);
声明友元函数:
friend Point operator–(Point&,int);
friend Point operator-(Point,Point);
friend ostream& operator<<(ostream &,Point p);
注意:若一个函数返回的是对象引用,则不返回auto型对象,需要静态存储的对象, 如static类型的对象
主函数中定义Point类的三个对象:p1、p2、p,p1、p2的初始值由键盘输入,p使用默认值。依次实现运算:p=++p1; p=p2–; p=p1+p2; p=p1-p2;后将结果输出。注意结果输出要求使用类似于“cout<<p1;”的形式。
输入描述
两个点的坐标
输出描述
进行++、–、+、-运算后各点的坐标
输入样例
10 9
4 5
输出样例
p=++p1后,p的坐标为:(11,10),p1坐标为:(11,10)
p=p2–后,p的坐标为:(4,5),p2坐标为:(3,4)
p=p1+p2后,p的坐标为:(14,14)
p=p1-p2后,p的坐标为:(8,6)

#include <iostream>
using namespace std;
class Point
{
private:
	int real, imag;
public:

	Point(int r = 0, int i = 0)
	{
		real = r;
		imag = i;
	}
	friend ostream& operator<<(ostream&, Point &);
	friend istream& operator>>(istream&, Point &);
	friend Point operator--(Point&, int);
	friend Point operator-(Point, Point);
	Point& operator++();
	Point& operator+(Point);
};

ostream& operator<<(ostream& output, Point &obj)
{

	output << "(" << obj.real << "," << obj.imag << ")";
	return output;
}

istream & operator>>(istream& input, Point &obj)

{

	input >> obj.real;
	input >> obj.imag;
	return input;
}

Point operator-(Point a, Point b)
{
	Point temp(0, 0);
	temp.real = a.real - b.real;
	temp.imag = a.imag - b.imag;
	return temp;

}
Point  &Point ::operator++()//单目运算符成员函数的返回值是this指针比如是return (*this)
{
	real++;
	imag++;
	return (*this);

}
Point  &Point ::operator+(Point a)
{
	static Point temp(0, 0);
	temp.real = real + a.real;
	temp.imag = imag + a.imag;
	return temp;

}
Point operator--(Point &op, int)//后置
{
	Point temp;
	temp = op;
	op.imag--;
	op.real--;
	return temp;
}


int main()
{
	Point p1, p2, p;
	cin >> p1 >> p2;
	p = ++p1;
	cout << "p=++p1后,p的坐标为:" << p << ",p1坐标为:" << p1 << endl;
	p = p2--;
	cout << "p=p2--后,p的坐标为:" << p << ",p2坐标为:" << p2 << endl;
	p = p1 + p2;
	cout << "p=p1+p2后,p的坐标为:" << p << endl;
	p = p1 - p2;
	cout << "p=p1-p2后,p的坐标为:" << p << endl;
	return 0;
}

  • 9
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bmNkotc2AECynaY6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值