#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();
}