c++ - Error when overloading insertion (<<) and addition (+) -
i'm learning c++ , baffling me. have vector
class plus , insertion operators overloaded:
#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); */ }
when try print vector
fine:
vector i(1, 0, 0); std::cout << i; // => "(1, 0, 0)"
adding vectors works fine also:
vector i(1, 0, 0); vector j(0, 1, 0); vector x = + j; std::cout << x; // => "(1, 1, 0)"
but if try print sum of 2 vectors without intermediary variable huge compile error don't understand:
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 ‘operator<<’ (operand types ‘std::ostream {aka std::basic_ostream<char>}’ , ‘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 ill-formed: vector.cpp:28:21: error: invalid initialization of non-const reference of type ‘vector&’ rvalue of type ‘vector’ std::cout << (i + j);
what doing wrong? should work?
the result of addition operator isn’t can take non-const
reference to. since you’re not modifying vector
in <<
, though, can , should make const
:
std::ostream &operator<<(std::ostream &out, const vector &v) { out << "(" << v.x << ", " << v.y << ", " << v.z << ")"; return out; }
Comments
Post a Comment