1

此代码的编译失败:

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<<但是在私有成员类的 cpp 文件中定义这样的正确方法是什么?

4

1 回答 1

5

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

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

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

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

如果您还需要访问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;
}
于 2019-04-23T20:20:29.680 回答