以下代码:
class A
{
friend class B;
int m;
};
class B
{
friend void f(A* p) { p->m = 32; }
};
在clang版本9.0.0-2中进行编译,但在g ++版本9.2.1中则未进行编译
friend-test.cpp: In function ‘void f(A*)’:
friend-test.cpp:10:28: error: ‘int A::m’ is private within this context
10 | friend void f(A* p) { p->m = 32; }
| ^
friend-test.cpp:5:7: note: declared private here
5 | int m;
| ^
哪个编译器是正确的?
GCC在右边。 Clang似乎有一个错误。
[[class.friend]
10友谊既不是继承的也不是传递的。 [示例:
class A { friend class B; int a; }; class B { friend class C; }; class C { void f(A* p) { p->a++; // error: C is not a friend of A despite being a friend of a friend } }; class D : public B { void f(A* p) { p->a++; // error: D is not a friend of A despite being derived from a friend } };
—例子]
f
是B
的朋友,而B
依次是A
的朋友并不意味着f
被允许访问A
的私有部分。