Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator<< for a nested private class possible?

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
like image 871
pms Avatar asked Nov 10 '11 15:11

pms


People also ask

Can we overload << operator?

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?

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.

What is operator overloading in OOPM?

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.


1 Answers

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)
    };
    //  ...
};
like image 89
James Kanze Avatar answered Sep 29 '22 01:09

James Kanze