Overloading operator<< for a nested private class possible?

烈酒焚心 提交于 2019-12-22 03:53:09

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/8082190/overloading-operator-for-a-nested-private-class-possible

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