【问题标题】:When overloading the << operator from std::ostream, why does the compiler give a "too many parameters for this operator function" error? [duplicate]从 std::ostream 重载 << 运算符时,为什么编译器会给出“此运算符函数的参数过多”错误? [复制]
【发布时间】: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


【解决方案1】:

使用friend,操作符不是类的成员,所以它需要2个输入参数。

没有friend,操作符成为类的成员,因此只需要1个参数,因此您需要删除vector2d参数并使用隐藏的this参数。

【讨论】:

  • 重载
  • @Ozymandias 不,当使用friend 时,但这也不是实现此目的的唯一方法。请参阅链接副本中的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
相关资源
最近更新 更多