编译此代码失败:
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:
使这个代码编译。它显然可以转移到班级本身。
但是在私有成员类的cpp文件中定义这样的operator<<
的正确方法是什么?
要查看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;
}