-1

I am currently programming an int matrix in cpp.

I wanted to add a printing function that prints the numbers in the following way:

1 2 3
7 6 9    
19 23 9

(every 2 intergers are seperated with a space, in the end of the line no space). so I wrote the following code:

std::ostream& IntMatrix::operator << (std::ostream& out) const
{
    for(int i = 0; i < this->num_row; i++)
    {
            int j;
            for(j = 0; j < this->num_col - 1; j++)
            {
                    out << this->mat[i][j] << " ";
            }
            out << this->mat[i][j] << endl;
    }
    return out;
}

which is in the file IntMatrix.cpp. however, every time I try to compile the code, this is what happens:

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

What to do?

  • Use the global operator overload. – πάντα ῥεῖ Aug 27 '15 at 15:33
  • 1
    Regardless of that error, try implementing a free function `ostream& operator << (ostream&, const IntMatrix&)` rather than the member `ostream& IntMatrix::operator << (ostream&) const`: the member operator would have to be invoked as `matrix << std::cout`, which is … unusual, and probably not what you wanted. See also the [operator overloading FAQ](http://stackoverflow.com/q/4421706/1521179) for tips on implementing operators. – amon Aug 27 '15 at 15:38

1 Answers1

0

Instead of a class member function use an overload for the global namespace:

 std::ostream& operator << (std::ostream& out, const IntMatrix& m) {
 }

and declare that one as friend of IntMatrix.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190