【发布时间】:2018-07-12 22:00:00
【问题描述】:
我有一个表示二维列向量的结构。我重载了一些运算符,例如 * 表示在 int 上下文中的标量乘法和 + 表示在另一个向量的上下文中的向量加法。
我还想重载
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;
}
};
这很好用,但是如果我删除了朋友关键字,我会得到“此运算符函数的参数太多”。这是什么意思,为什么朋友关键字会修复它?
【问题讨论】:
-
使用c++的编程原理与实践。 Bjarne Strousrupp。
标签: c++ operator-overloading cout ostream