Overloading operator<< for a nested private class possible?

给你一囗甜甜゛ 提交于 2019-12-05 01:46:40

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 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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!