对于Point类:
class Point
{
public:
Point(float x, float y):_x(x), _y(y){}
private:
float _x, _y;
}
测试代码的main函数:
int main()
{
Point a(1, 2),c;
Point b(3, 4);
c = b - a;
cout << b << "-" << a << "=" << c;
}
重载输出运算符<<:
class Point
{
//重载的输出操作符声明为类的友元函数
friend ostream& operator<<(ostream& o, const Point& p);
public:
Point(float x, float y):_x(x), _y(y){}
private:
float _x, _y;
}
//重载为全局函数
ostream& operator<<(ostream& o, const Point& p)
{
o << "[" << p.x << "," << p.y << "]"; //这里使用的以前的输出运算符<<
return o;
}
运行结果: