【问题标题】:operator<< overload in C++ not working as expectedC++ 中的 operator<< 重载无法按预期工作
【发布时间】:2021-01-17 09:29:06
【问题描述】:

我已经定义了一个类模板MyVector 并重载了operator&lt;&lt; 以打印它所包含的向量。

//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&lt;&lt; 会抛出:

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
}

我在这里错过了什么?

【问题讨论】:

  • 只有当您打算修改参数时,才应将参数作为左值引用传递。在任何其他情况下,通过值或 const 引用传递(以避免昂贵的复制)

标签: c++ operator-overloading operator-keyword


【解决方案1】:

您在MyVector 上的operator+ 返回一个临时的:

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

不能绑定到operator&lt;&lt; 期望的非常量引用:

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

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

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

同样,您的 operator+ 应该通过 const 引用来接受它的参数,并且也应该是 const 限定的:

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

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

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

【讨论】:

  • operator+ 参数也应该是const 引用以防止下一个问题,为什么a + b + c 不起作用。
  • 非常感谢!!!这很有帮助,我对 C++ 还很陌生,但我仍然很难理解那些“const”参数。
  • 没问题 :) 如果答案回答了您的问题,请考虑接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 2016-04-24
相关资源
最近更新 更多