pms
pms

Reputation: 4626

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

Upvotes: 17

Views: 5724

Answers (2)

sohorx
sohorx

Reputation: 101

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;
}

Upvotes: 10

James Kanze
James Kanze

Reputation: 153899

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)
    };
    //  ...
};

Upvotes: 17

Related Questions