相关疑难解决方法(0)

为什么C++好友类只需要在其他命名空间中使用前向声明?

假设我有一个类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)

c++ namespaces friend forward-declaration

46
推荐指数
2
解决办法
3万
查看次数

标签 统计

c++ ×1

forward-declaration ×1

friend ×1

namespaces ×1