此代码编译失败:
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/