<分区>
我有一个表示二维列 vector 的结构。我已经重载了一些运算符,例如 * 表示在 int 上下文中的标量乘法和 + 表示在另一个 vector 的上下文中的 vector 加法。
我还想重载 << 运算符,以便我可以简单地将对象传递给 cout 并打印两个元素。目前我正在重载它,如下所示;
struct vector2d
{
private:
float x;
float y;
public:
vector2d(float x, float y) : x(x), y(x) {}
vector2d() : x(0), y(0) {}
vector2d operator+(const vector2d& other)
{
this->x = this->x + other.x;
this->y = this->y + other.y;
return *this;
}
vector2d operator*(const int& c)
{
this->x = this->x*c;
this->y = this->y*c;
return *this;
}
friend std::ostream& operator<<(std::ostream& out, const vector2d& other)
{
out << other.x << " : " << other.y;
return out;
}
};
这工作正常,但如果我删除 friend 关键字,我会得到“此运算符函数的参数过多”。这是什么意思,为什么 friend 关键字修复了它?