对于Point类:
class Point
{
public:
Point(float xx, float yy) :x(xx), y(yy) {}
void Show() //显示输出函数
{
cout << "[" << x << "," << y << "]";
}
private:
float x, y;
};
减法重载为全局函数:
往往声明为类的友元函数
class Point
{
//重载的全局函数声明为类的友元函数
friend Point operator-(const Point& p1, const Point& p2);
public:
Point(float xx, float yy) :x(xx), y(yy) {}
void Show() //显示输出函数
{
cout << "[" << x << "," << y << "]";
}
private:
float x, y;
};
//类外实现
Point operator-(const Point& p1, const Point& p2)
{
return Point(p1.x - p2.x, p1.y - p2.y);
}
int main()
{
Point a(1, 2),c;
Point b(3, 4);
c = b - a;
c.Show();
}