c++ - 从 std::ostream 重载 << 运算符时,为什么编译器会给出 "too many parameters for this operator function"错误?

标签 c++ operator-overloading cout ostream

<分区>

我有一个表示二维列 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 关键字修复了它?

最佳答案

对于 friend,运算符不是类的成员,因此需要 2 个输入参数。

没有friend,运算符成为类的成员,因此只需要1个参数,所以您需要删除vector2d参数并使用隐藏的this 参数代替。

关于c++ - 从 std::ostream 重载 << 运算符时,为什么编译器会给出 "too many parameters for this operator function"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51315078/

相关文章:

c++ - 在 Windows 的 GUI 应用程序中使用控制台,仅当它从控制台运行时

c++ - 套接字发送/接收问题 : second client message never reaches server

c++ - DevIL/OpenIL 未加载 alpha channel

c++ - 如何修复以前工作的注入(inject)模板友元函数?

c++ - 交换运算符+重载导致无限递归

c++ - 检查 C 和 C++ 中的输出错误

c++ - 执行时动态库链接

具有自定义类的 C++ 动态二维数组

c# - 可以得到 "operator"结果的引用吗?

c++ - 在 "cout"语句中调用具有 "cout"语句的函数