好久没有写操作符重载了 自己重新写了个 温习了一下细节 温习友元 this const 引用

#include <iostream>
using namespace std;

class Point
{
public:
	Point(int _x, int _y) : x(_x), y(_y)
	{}

	void setPoint(int _x,int _y)
	{
		x = _x;
		y = _y;
	}

	void print()
	{
		cout<<"< "<<x<<ends<<y<<" >"<<endl;
	}

	friend Point operator+(const Point& a, const Point& b);	//这里写友元是因为此函数不属于该类的成员函数 又要操作该类的私有成员变量

	Point operator-(const Point& b);//类成员重载操作符 不能传2个参数 因为有个this指针占一个 this指针代表自己
private:
	int x;
	int y;
};

Point operator+(const Point& a, const Point& b)//引用是为了避免调用+操作符时将形参传给实参的开销 const是为了使用引用之后避免修改了参数的值 导致外部参数被改
{
	Point s(0,0);
	s.setPoint(a.x+b.x, a.y+b.y);
	return s;
}

Point Point::operator -(const Point& b)
{
	Point s(0,0);
	s.setPoint(this->x-b.x, this->y-b.y);//类成员重载操作符 利用this指针进行操作
	return s;
}

void main()
{
	Point a(3,7);
	Point b(4,8);
	Point c(0,0);

	(a+b).print();				//7 15
	operator+(a,b).print();		//7 15

	(b-a).print();				//1 1
	//c = a+b;
	//c.print();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值