问题
How one can overload an operator<< for a nested private class like this one?
class outer {
private:
class nested {
friend ostream& operator<<(ostream& os, const nested& a);
};
// ...
};
When trying outside of outer class compiler complains about privacy:
error: ‘class outer::nested’ is private
回答1:
You could make the operator<<
a friend of outer
as well. Or you
could implement it completely inline
in nested
, e.g.:
class Outer
{
class Inner
{
friend std::ostream&
operator<<( std::ostream& dest, Inner const& obj )
{
obj.print( dest );
return dest;
}
// ...
// don't forget to define print (which needn't be inline)
};
// ...
};
回答2:
if you want the same thing in two different file (hh, cpp) you have to friend two time the function as follow:
hh:
// file.hh
class Outer
{
class Inner
{
friend std::ostream& operator<<( std::ostream& dest, Inner const& obj );
// ...
};
friend std::ostream& operator<<( std::ostream& dest, Outer::Inner const& obj );
// ...
};
cpp:
// file.cpp:
#include "file.hh"
std::ostream &operator<<( std::ostream& dest, Outer::Inner const& obj )
{
return dest;
}
来源:https://stackoverflow.com/questions/8082190/overloading-operator-for-a-nested-private-class-possible