简体   繁体   中英

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

I have defined a class template MyVector and overloaded the operator<< to print the vector that it holds.

//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;
}

The operator seems to work fine for simple use cases, but when adding 2 instances of MyVector , the operator<< throws an:

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
}

What am I missing here?

Your operator+ on MyVector returns a temporary:

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

which can't bind to a non-const reference which operator<< expects:

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

You can fix this by accepting a const reference instead:

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

Similarly, your operator+ should take it's argument by const reference, and also should be const-qualified:

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

to allow expressions like this to work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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