繁体   English   中英

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

[英]operator<< overload in C++ not working as expected

我已经定义了一个类模板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
}

我在这里缺少什么?

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

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

它不能绑定到operator<<期望的非常量引用:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM