重载插入(<<)和加法(+)时出错 [英] Error when overloading insertion (<<) and addition (+)

查看:184
本文介绍了重载插入(<<)和加法(+)时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C++,这让我感到困惑。我有一个重载了加号和插入操作符的Vector类:

#include <iostream>

class Vector {
    public:
        Vector(float _x, float _y, float _z) {
            x = _x; y = _y; z = _z;
        }

        float x, y, z;
};

Vector operator+(const Vector &v1, const Vector &v2) {
    return Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
}

std::ostream &operator<<(std::ostream &out, Vector &v) {
    out << "(" << v.x << ", " << v.y << ", " << v.z << ")";

    return out;
}


int main() {
    Vector i(1, 0, 0);
    Vector j(0, 1, 0);

    std::cout << i;
    /* std::cout << (i + j); */

}

当我尝试打印Vector时,一切正常:

Vector i(1, 0, 0);
std::cout << i;  // => "(1, 0, 0)"

添加向量也很有效:

Vector i(1, 0, 0);
Vector j(0, 1, 0);
Vector x = i + j;
std::cout << x;  // => "(1, 1, 0)"

但是,如果我尝试打印两个向量之和而没有中间变量,我会得到一个巨大的编译错误,我真的不明白:

Vector i(1, 0, 0);
Vector j(0, 1, 0);
std::cout << (i + j);  // Compile Error

vector.cpp: In function ‘int main()’:
vector.cpp:28:15: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘Vector’)
     std::cout << (i + j);
               ^
vector.cpp:17:15: note: candidate: std::ostream& operator<<(std::ostream&, Vector&) <near match>
 std::ostream &operator<<(std::ostream &out, Vector &v) {
               ^
vector.cpp:17:15: note:   conversion of argument 2 would be ill-formed:
vector.cpp:28:21: error: invalid initialization of non-const reference of type ‘Vector&’ from an rvalue of type ‘Vector’
     std::cout << (i + j);

我做错了什么?这真的管用吗?

推荐答案

加法运算符的结果不能进行非const引用。但是,由于您没有在<<中修改Vector,所以您可以且应该将其设置为const

std::ostream &operator<<(std::ostream &out, const Vector &v) {
    out << "(" << v.x << ", " << v.y << ", " << v.z << ")";

    return out;
}

这篇关于重载插入(&lt;&lt;)和加法(+)时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆