假设我有一堂课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;
};
} // namespace A
class F {
public:
F() { g.g = 3; c.c = 2; }
private:
G g;
A::C c;
};
int main()
{
F f;
}
对我来说这似乎不一致。这是有原因的还是只是标准的设计决定?
C++
标准ISO/IEC 14882:2003(E)
7.3.1.2 命名空间成员定义
第 3 段
每个名字首先声明在
命名空间是该组织的成员
名称空间。如果朋友声明
非局部类首先声明一个
类或函数
(这意味着类或函数的名称是不合格的)友元类
或函数是成员
最内层的封闭命名空间。
// 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) { /* ... */} // definition of A::f
void h(int) { /* ... */ } // definition of A::h
// A::f, A::g and A::h are visible here and known to be friends
}
Your friend class BF;
是一个声明A::BF
在命名空间 A 而不是全局命名空间中。您需要全局事先声明来避免此新声明。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)