c++ - 可以为嵌套的私有(private)类重载 operator<< 吗?

标签 c++ nested operator-overloading nested-class

如何为像这样的嵌套私有(private)类重载运算符<<?

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

在外部类编译器之外尝试时会提示隐私问题:

error: ‘class outer::nested’ is private

最佳答案

你可以制作 operator<< outer的 friend 以及。或者您 可以完全实现它inlinenested ,例如:

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

关于c++ - 可以为嵌套的私有(private)类重载 operator<< 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8082190/

相关文章:

c++ - g++: 没有那个文件或目录?

C++ 嵌套类前向声明​​错误

c - while 循环和嵌套 if 不能一起工作

c# - 为可空类型重载 = 运算符?

C++ 编译错误

c++ - () 运算符重载 C++

c++ - 直接访问硬盘?

java - 在 Java 中实现曾经是 Mixin 的正确方法?

c++ - EnumDisplaySettings 最大模式数

c - C中的嵌套结构