Why does a C++ friend class need a forward declaration only in other namespaces?(为什么 C++ 友元类只需要在其他命名空间中进行前向声明?)
问题描述
假设我有一个类 F
应该是类 G
(在全局命名空间中)和 C
(在命名空间 <代码>A).
Suppose I have a class F
that should be friend to the classes G
(in the global namespace) and C
(in namespace A
).
- 要成为
A::C
的朋友,F
必须前向声明. - 要成为
G
的朋友,F
的前向声明是不必要的. - 同样,类
A::BF
可以成为A::C
的朋友,无需前向声明
- to be friend to
A::C
,F
must be forward declared. - to be friend to
G
, no forward declaration ofF
is necessary. - likewise, a class
A::BF
can be friend toA::C
without forward declaration
以下代码说明了这一点,并可以使用 GCC 4.5、VC++ 10 以及至少一个其他编译器进行编译.
The following code illustrates this and compiles with GCC 4.5, VC++ 10 and at least with one other compiler.
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;
};
} // namespace A
class F {
public:
F() { g.g = 3; c.c = 2; }
private:
G g;
A::C c;
};
int main()
{
F f;
}
在我看来,这似乎不一致.这是有原因的还是只是标准的设计决定?
To me this seems inconsistent. Is there a reason for this or is it just a design decision of the standard?
推荐答案
C++
标准ISO/IEC 14882:2003(E)
7.3.1.2 命名空间成员定义
第 3 段
每个名字首先在一个命名空间是其中的一个成员命名空间.如果朋友声明在一个非本地类首先声明一个类或函数(这意味着类或函数的名称是不合格的)朋友类或函数是最里面的封闭命名空间.
Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local class first declares a class or function (this implies that the name of the class or function is unqualified) the friend class or function is a member of the innermost enclosing namespace.
// Assume f and g have not yet been defined.
void h(int);
template <class T> void f2(T);
namespace A {
class X {
friend void f(X); // A::f(X) is a friend
class Y {
friend void g(); // A::g is a friend
friend void h(int); // A::h is a friend
// ::h not considered
friend void f2<>(int); // ::f2<>(int) is a friend
};
};
// A::f, A::g and A::h are not visible here
X x;
void g() { f(x); } // definition of A::g
void f(X) { /* ... *
本文标题为:为什么 C++ 友元类只需要在其他命名空间中进行前向声明?
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01