0

Hello everonye even I found many answers here about this questions one simply could not explain me how things going could not fix it trying everything.

So my question is I have a class called Matrix when I try to implement operator << as inline method I get following error

 error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’

Here is how implementation of my method looks in class

 ostream& operator<<(ostream& out)
{

    for (int i = 0; i < this->getHeight(); ++i) {
        for (int j = 0; j < this->getWidth(); ++j) {

            out << this->(i, j) << "\t";
        }
        out<< "\n";
    }

    return out;
}

When I implement it as function like this

    template <typename U>
ostream& operator<<(ostream& out, const Matrix<U>& c)
{

    for (int i = 0; i < c.getHeight(); ++i) {
        for (int j = 0; j < c.getWidth(); ++j) {

            out << c(i, j) << "\t";
        }
        out << "\n";
    }

    return out;
} 

It works :( Can anyone explain me what I m doing wrong here

1 Answers1

1

std::ostream& Matrix<U>::operator <<(std::ostream&) has the equivalent free-function signature std::ostream& operator <<(Matrix<U>&, ostream&), which is not what you want (for multiple reasons).

It is not possible to implement streaming operator << or operator >> as a member function of a UDT, because the first parameter must always be the stream. You could make the operator a friend, in which case the signature would need to be:

template <typename U>
friend std::ostream& operator <<(std::ostream&, Matrix const&);

(Again, note that the stream comes first, like in your working code.)

Your templated operator << looks just fine. What's your objection to it?

ildjarn
  • 62,044
  • 9
  • 127
  • 211