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 x,y;
public:
//成员运算符重载
	Point& operator++();
	Point& operator+(Point);
	Point(int x = 0, int y = 0) :x(x), y(y){}
//友元运算符重载
	friend Point operator--(Point&, int);
	friend Point operator-(Point, Point);

	friend ostream& operator<<(ostream&os, Point p)//输出整个坐标
	{
		cout << "(" << p.x <<","<< p.y << ")" << endl;
		return os;
	}
};

Point &Point ::operator+(Point a) {
	Point temp;
	temp.x = x + a.x;
	temp.y = y + a.y;
	return temp;
}

Point &Point ::operator++() //先自增则p=p1,都输出p1坐标即可
{
	++x;
	++y;
	return *this;

}

Point operator--(Point&op, int)   //要输出两个不同坐标!!!
{
	Point temp = op;              //区分p和p2坐标
	--op.x;
	--op.y;
	return temp;
}

Point operator-(Point p1, Point p2)
{
	Point temp;
	temp.x = p1.x - p2.x;
	temp.y = p1.y - p2.y;
	return temp;
}


int main()
{
	int x1, x2, y1, y2;
	cin >> x1 >> y1 >> x2 >> y2;
	Point p1(x1, y1), p2(x2, y2);
	Point p;
	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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

扶1

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

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

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

打赏作者

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

抵扣说明:

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

余额充值