如何在 .cpp 文件中而不是在标头中为私有类成员定义友元运算符 << ?

Jen*_* M. 1 c++ operator-overloading stream friend inner-classes

这段代码编译失败:

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

Run Code Online (Sandbox Code Playgroud)

错误:

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.
Run Code Online (Sandbox Code Playgroud)

取消注释public:会使该代码能够编译。它显然可以转移到班级本身。

operator<<但是在 cpp 文件中为私有成员类定义此类的正确方法是什么?

Chr*_*phe 5

要看到 的私人元素P,您operator<<必须是 的朋友P。因此,为了能够访问类的定义C

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

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

std::ostream& operator<<(std::ostream &os, const P::C &c) {
  return os;
}
Run Code Online (Sandbox Code Playgroud)

如果您还需要访问您的私人成员,C您需要成为双重好友:

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;
}
Run Code Online (Sandbox Code Playgroud)