Search code examples
c++namespacesoperator-overloadingiostreamostream

How can I properly overload the << operator for an ostream?


I am writing a small matrix library in C++ for matrix operations. However, my compiler complains, where before it did not. This code was left on a shelf for six months and in between I upgraded my computer from Debian 4.0 (Etch) to Debian 5.0 (Lenny) (g++ (Debian 4.3.2-1.1) 4.3.2). However, I have the same problem on a Ubuntu system with the same g++.

Here is the relevant part of my matrix class:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
    }
}

And the "implementation":

using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

    [...]

}

This is the error given by the compiler:

matrix.cpp:459: error: 'std::ostream& Math::Matrix::operator<<(std::ostream&, const Math::Matrix&)' must take exactly one argument

I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those six months. :-)


Solution

  • You have declared your function as friend. It's not a member of the class. You should remove Matrix:: from the implementation. friend means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for Matrix class which is wrong.