我正在学习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);
我做错了什么?这应该工作吗?
答案 0 :(得分:4)
加法运算符的结果不是你可以采用非const
引用的。但是,由于您未在Vector
中修改<<
,因此您可以而且应该将其const
:
std::ostream &operator<<(std::ostream &out, const Vector &v) {
out << "(" << v.x << ", " << v.y << ", " << v.z << ")";
return out;
}