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
To get cout to accept a Date object after the insertion operator, overload the insertion operator to recognize an ostream object on the left and a Date on the right. The overloaded << operator function must then be declared as a friend of class Date so it can access the private data within a Date object.
Why must << be overloaded as a friend function? It is not necessary. It is usually done because this function often accesses the private and protected members of the object it displays. overloaded operator<< or operator>> function.
Physical Data Design Considerations. Polymorphism: Polymorphism (or operator overloading) is a manner in which OO systems allow the same operator name or symbol to be used for multiple operations. That is, it allows the operator symbol or name to be bound to more than one implementation of the operator.
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)
};
// ...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With