重载运算符<<对于嵌套私有类可能吗?

Overloading operator<< for a nested private class possible?

本文关键字:lt 运算符 于嵌套 嵌套 重载      更新时间:2023-10-16

如何重载操作符<<对于像这样的嵌套私有类?

class outer {
  private:
    class nested {
       friend ostream& operator<<(ostream& os, const nested& a);
    };
  // ...
};

当尝试外部类编译器抱怨隐私:

error: ‘class outer::nested’ is private

您也可以将operator<<设置为outer的朋友。或者你可以在nested中完全实现inline,例如:

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

如果您想在两个不同的文件(hh, cpp)中使用相同的内容,则必须在两个时间内设置函数,如下所示:

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