I have a private enum in a class within a namespace. I'm trying to overload the I/O operators, but all I get is the compiler complaining about the Enum being private. The solution from this post did nothing to help me. Here is an isolated version of my problem.
TestClass.h
#include <iostream>
namespace Test
{
class TestClass
{
enum Enum : unsigned int {a = 0, b};
friend std::ostream& operator<<(std::ostream& os, Enum e);
};
std::ostream& operator<<(std::ostream& os, TestClass::Enum e);
};
TestClass.cpp
#include "TestClass.h"
std::ostream& operator<<(std::ostream& os, Test::TestClass::Enum e)
{
//do it
}
The compiler complains about this, but does not complain when I remove the class from the namespace, so how do I get this to compile?
I'm using
g++ -c TestClass.h
to compile this
The operator in your cpp file is not the friend you declared. The friend is a member of the namespace, because the class it's declared in is a member.
So wrap the operator definition in the namespace scope too. Or fully qualify the defintion
std::ostream& Test::operator<<(std::ostream& os, Test::TestClass::Enum e)
{
//do it
}