假设我有一个类F应该是类G(在全局命名空间中)和C(在命名空间中A)的朋友.
A::C,F必须向前宣布.G,没有F必要的前瞻性声明.A::BF可以成为朋友而A::C无需前瞻性声明下面的代码说明了这一点,并使用GCC 4.5,VC++ 10以及至少与另一个编译器进行编译.
class G {
friend class F;
int g;
};
// without this forward declaration, F can't be friend to A::C
class F;
namespace A {
class C {
friend class ::F;
friend class BF;
int c;
};
class BF {
public:
BF() { c.c = 2; }
private:
C c;
};
} // …Run Code Online (Sandbox Code Playgroud)