I'm trying to overload the << operator for a nested private class.
I have a situation like:
class A
{
public:
class B
{
private:
int i;
};
};
ostream& operator<<(ostream& output, const A::B& b)
{
cout << "I= " << b.i ;
}
Where the last command denies me access toi because of its private access level.
How would I rewrite the operator overload above to allow me to do this?
Its not the operator, its the private thats causing the problem, use an access function inside the class to allow access the the private.
Something like:
1 2 3
void display(ostream& o) {
o << "I= " << i << endl;
}
If you use this inside the class then you overcome the private access problem, then you can overload the operator to do:
1 2 3 4
ostream& operator<<(ostream& o, const A::B& b) {
b.display(o);
return o;
}
Its generally not a great idea to just add friends to classes, although it should be fine with the ostream's it could cause problems with other things.