0

我正在尝试将 << 运算符重载为非成员重载运算符,以使其在对象的内容上打印数据。

Point2D.h

//Point2D.h

class Point2D
{
 public:
  double x=0.0;
  double y=0.0;
  Point2D(double in_x=0.0, double in_y=0.0);
};

double GetDistanceBetween(Point2D p1, Point2D p2);

Point2D operator<<(Point2D p1);

然后在 Point2D.cpp 文件中我有

//Point2D.cpp
#include "Point2D.h"
#include <math.h>

Point2D::Point2D(double in_x, double in_y)
  : x(in_x), y(in_y) {}

double GetDistanceBetween(Point2D p1, Point2D p2)
{
  double xdiff = p2.x - p1.x;
  double ydiff = p2.y - p1.y;
  xdiff = xdiff * xdiff;
  ydiff = ydiff * ydiff;
  xdiff = xdiff + ydiff;
  return sqrt(xdiff);
}

Point2D operator << (Point2D p1)
{
  cout << "(" << p1.x << ", " << p1.y << ")\n";
}

但我的错误是

In file included from TestCheckpoint1.cpp:3:0:
Point2D.h:13:30: error: 'Point2D operator<<(Point2D)' must take exactly two arguments
 Point2D operator<<(Point2D p1);
                              ^
Point2D.cpp:18:32: error: 'Point2D operator<<(Point2D)' must take exactly two arguments
 Point2D operator << (Point2D p1)
4

0 回答 0