c++ - 将重载运算符 << 与运算符 * 一起使用时出错

标签 c++ operator-overloading

我最近尝试过运算符重载,并查看了这个关于运算符重载的 stackoverflow 页面 (http://stackoverflow.com/questions/4421706/operator-overloading)。

我重载了 * 运算符,可以运行如下代码

Vector2 a(2, 3);
Vector2 b(5, 8);
Vector2 c = a*b;

但得到编译时错误error: invalid operands to binary expression ('basic_ostream<char, std::char_traits<char> >' and 'Vector2')

运行如下代码时

std::cout << a*b;

这里是Vector2.cpp

#include "Vector2.h"

Vector2::Vector2(const float x, const float y) {
    this->x = x;
    this->y = y;
}

Vector2 &Vector2::operator*=(const Vector2 &rhs) {
    this->x *= rhs.x;
    this->y *= rhs.y;
    return *this;
}

std::ostream &operator<< (std::ostream &out, Vector2 &vector) {
    return out << "(" << vector.x << ", " << vector.y << ")";
}

这里是 Vector2.h

#include <iostream>

class Vector2 {
    public:
        float x;
        float y;

        Vector2(const float x, const float y);
        Vector2 &operator*=(const Vector2 &rhs);
};

inline Vector2 operator*(Vector2 lhs, const Vector2 &rhs) {
    lhs *= rhs;
    return lhs;
}

std::ostream &operator<<(std::ostream &out, Vector2 &vector);

我不确定从这里到哪里去。

最佳答案

问题是

a*b

返回一个临时的,所以你需要:

std::ostream &operator<<(std::ostream &out, const Vector2 &vector);
//                                            |
//                                      notice const                                                  

因为临时不能绑定(bind)到非常量引用。

关于c++ - 将重载运算符 << 与运算符 * 一起使用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10760462/

相关文章:

c++ - 霍夫曼编码 - 伪 EOF

c++ - 重载运算符,这个例子中重载运算符的目的是什么

c++ - 在C/C++中快速读取多个文件的某些字节

pointers - 通过指针访问类型后派生类型中 Fortran 字符串的奇怪行为

c++ - 在 C++ 中重载比较运算符,如何与 const 参数进行比较?

c++ - 具有运算符重载和模板的未解析的外部符号

java - 如何修改现有的 Java 类以重载 Groovy 中的运算符?

C++14 TS 功能和 GCC 4.8

C++ - 图像处理库还是计算机视觉库?

c++ - 在具有引用成员的对象上使用放置 `new` 的结果