Overloading operator<<: cannot bind ‘std::basic_ostream’ lvalue to ‘std::basic_ostream&&’

后端 未结 2 1171
一个人的身影
一个人的身影 2021-01-23 21:40

Searching for the title of this question gives me a number of people quoting the same error, but under different circumstances, and unfortunately the answers there provided are

相关标签:
2条回答
  • 2021-01-23 21:55

    FIRST PROBLEM:

    To make your program compile, just use an lvalue reference to const as the second parameter of your operator << (both in the friend-declaration and in the definition of that function):

    template < class U, unsigned int M >
    std::ostream& operator<< ( std::ostream &out, Vector< U, M > const& cVector )
    //                                                           ^^^^^
    

    The reason why your program won't compile is that your overload of operator << accepts an lvalue reference to non-const as its second argument, and lvalue references to non-const cannot bind to rvalues.

    Since the result of operator + between two instances of Vector is a temporary, and a temporary is an rvalue, the compiler can't invoke your operator <<, and is therefore unable to resolve the call.

    SECOND PROBLEM:

    Once you fixed the above issue, you'll have to solve a second one: your Vector class template does not provide a const version of operator [], so your rewritten operator <<, which now accepts a reference to a const vector, won't be able to access the vector's elements.

    template < class T, unsigned int N >
    class Vector
    {
        // ...
    
        T& operator[] ( const unsigned int& );
    
        T const& operator[] ( const unsigned int& ) const; // <== ADD THIS!
    
        // ...
    };
    

    And of course the corresponding definition:

    template < class T, unsigned int N >
    T const& Vector< T, N >::operator[] ( const unsigned int &index ) const
    {
        return _values[ index ];
    }
    
    0 讨论(0)
  • 2021-01-23 22:05

    Change this:

    std::ostream& operator<< ( std::ostream&, Vector< U, M >& );
    

    to this:

    std::ostream& operator<< ( std::ostream&, const Vector< U, M >& );
    //                                        ^^^^^
    

    The compiler is telling you that C++ will not let you bind a temporary Vector such as u + v to a non-const Vector&.

    And you don't modify that Vector, so it should be const to begin with.

    0 讨论(0)
提交回复
热议问题