簡體   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