gpt4 book ai didi

c++ - 重载插入(<<)和添加(+)时出错

转载 作者:行者123 更新时间:2023-11-30 01:47:57 24 4
gpt4 key购买 nike

我正在学习 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 也可以正常工作:

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

但是如果我尝试在没有中间变量的情况下打印两个 vector 的总和,我会得到一个巨大编译错误,我真的不明白:

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;
}

关于c++ - 重载插入(<<)和添加(+)时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30946437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com