operator << must take exactly one argument

As As picture As As · May 24, 2012 · Viewed 105.3k times · Source

a.h

#include "logic.h"
...

class A
{
friend ostream& operator<<(ostream&, A&);
...
};

logic.cpp

#include "a.h"
...
ostream& logic::operator<<(ostream& os, A& a)
{
...
}
...

When i compile, it says:

std::ostream& logic::operator<<(std::ostream&, A&)' must take exactly one argument.

What is the problem?

Answer

Cat Plus Plus picture Cat Plus Plus · May 24, 2012

The problem is that you define it inside the class, which

a) means the second argument is implicit (this) and

b) it will not do what you want it do, namely extend std::ostream.

You have to define it as a free function:

class A { /* ... */ };
std::ostream& operator<<(std::ostream&, const A& a);