Why can't operator<<
function for streaming objects to std::cout
or to a file be a member function?
Let's say you have:
struct Foo
{
int a;
double b;
std::ostream& operator<<(std::ostream& out) const
{
return out << a << " " << b;
}
};
Given that, you cannot use:
Foo f = {10, 20.0};
std::cout << f;
Since operator<<
is overloaded as a member function of Foo
, the LHS of the operator must be a Foo
object. Which means, you will be required to use:
Foo f = {10, 20.0};
f << std::cout
which is very non-intuitive.
If you define it as a non-member function,
struct Foo
{
int a;
double b;
};
std::ostream& operator<<(std::ostream& out, Foo const& f)
{
return out << f.a << " " << f.b;
}
You will be able to use:
Foo f = {10, 20.0};
std::cout << f;
which is very intuitive.