c++ - 如何在 .cpp 文件中为私有(private)类成员定义 friend operator<< 而不是在 header 中?

标签 c++ stream operator-overloading inner-classes friend

此代码编译失败:

class P {
//public:
  class C {
  friend std::ostream& operator<<(std::ostream &os, const C &c);
  };
};


std::ostream& operator<<(std::ostream &os, const P::C &c) {
  return os;
}

错误:

test.cpp:12:53: error: 'C' is a private member of 'P'
std::ostream& operator<<(std::ostream &os, const P::C &c) {
                                                    ^
test.cpp:6:9: note: implicitly declared private here
  class C {
        ^
1 error generated.

取消注释 public:使此代码编译。它显然可以移动到类本身。

但是定义这样的 operator<< 的正确方法是什么?在私有(private)成员类的 cpp 文件中?

最佳答案

查看 P 的私有(private)元素, 你的 operator<<必须是 P 的 friend .所以为了能够访问类 C 的定义:

class P {
  class C {
      ...
  };
  friend std::ostream& operator<<(std::ostream &os, const C &c);
};

然后,您当前的运算符将进行编译。但它只能访问C的公共(public)成员, 因为它是封闭的 friend P但不是嵌套的 C :

std::ostream& operator<<(std::ostream &os, const P::C &c) {
  return os;
}

如果你还需要访问C的私有(private)成员你需要成为双重 friend :

class P {
  class C {
    int x;   //private 
    friend std::ostream& operator<<(std::ostream &os, const C &c);  // to access private x
  };
  friend std::ostream& operator<<(std::ostream &os, const C &c); // to access private C
};

std::ostream& operator<<(std::ostream &os, const P::C &c) {
  os<<c.x; 
  return os;
}

关于c++ - 如何在 .cpp 文件中为私有(private)类成员定义 friend operator<< 而不是在 header 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55818527/

相关文章:

c++ - 如何在两个不同类之间重载 '==' 运算符?

c++ - 在类实例化期间未设置继承值

c++ - 如何将 std::vector<std::string> 转换为 boost::spirit 中结构的成员?

javascript - RxJS 中的 bufferReduce

video - 上传视频,按大小拆分(在 mb 上)并播放

c++ - 转换运算符(赋值运算符=)没有响应

c++ - 如何输出乘以用户创建的类c++

C++ 嵌套结构的 typedef(元类)编译错误

c++ - 返回一个 vector 作为参数

c++ - 一次处理许多流操作