C++ 中的 operator<< 重载未按预期工作

operator<< overload in C++ not working as expected

我定义了一个 class 模板 MyVector 并重载了 operator<< 以打印它包含的向量。

//MyVector definition
template<int n, typename T>
class MyVector{


  private:
    vector<T> vetor;
  public:
    //Several Methods
    MyVector operator+(MyVector& v){
        //Adds 2 vectors
    }

   template<typename U, int m>
   friend ostream& operator << (ostream& o, MyVector<m,U>& v);
};

template<typename T, int n>
ostream& operator << (ostream& o, MyVector<n,T> &v){
  o << "[";
  for(auto itr = v.vetor.begin(); itr != v.vetor.end()-1; ++itr){
    o << *itr <<", ";
  }
  o << v.vetor.back() << "]";
  return o;
}

运算符似乎适用于简单的用例,但是当添加 2 个 MyVector 实例时,operator<< 抛出:

invalid operands to binary expression
int main(){
  MyVector<2,int> v1;
  MyVector<2,int> v2;
  MyVector<2,int> v3;

  v1.add(1,2);
  v2.add(3,4);
  v3 = v1+v2;

  cout << v3 << endl;  // --> This prints "[7,11]" to the console
  cout << v1+v2 << endl; // --> This throws the exception
}

我在这里错过了什么?

你的 operator+ MyVector returns 一个临时的:

   MyVector operator+(MyVector& v);
// ^^^^^^^^ temporary 

无法绑定到 operator<< 期望的 non-const 引用:

ostream& operator << (ostream& o, MyVector<m,U>& v);
                               // ^^^^^^^^^^^^^^  non-const reference

您可以通过接受 const 引用来解决此问题:

ostream& operator << (ostream& o, MyVector<m,U> const & v);
                                             // ^^^^^

同样,你的 operator+ 应该通过 const 引用来接受它的参数,也应该是 const-qualified:

MyVector operator+(MyVector const & v) const;
                         // ^^^^^      ^^^^^

允许这样的表达式起作用:

MyVector<2, int> const v = // ...
std::cout << v + v + v;