友元函数 f
无权访问封闭类 A
的私有(private)成员。
#include <iostream>
class A{
const static int p = 1;
class B {
friend void f() {
std::cout << p << '\n';
std::cout << q << '\n';
}
};
public:
const static int q = 2;
};
void f();
int main()
{
f();
}
至少,我认为 N4140 中的 [class.nest]/4 是这样说的(见下文)。
§9.7/4
Like a member function, a friend function (11.3) defined within a nested class is in the lexical scope of that class; it obeys the same rules for name binding as a static member function of that class (9.4), but it has no special access rights to members of an enclosing class.
最佳答案
我相信您是正确的,因为 Visual Studio 和 GCC 根据您引用的规范正确拒绝了代码。通过允许从友元函数 f()
访问 A
的私有(private)成员变量 p
,Clang 似乎出错了,因为 f()
是 B
的 friend ,而不是 A
。
有关友元函数范围的良好讨论,请参阅以下 SO 帖子中投票最多的答案:What's the scope of inline friend functions
关于c++ - 我相信 clang 错误地允许内联友元函数访问封闭范围内的数据。 gcc 和 vs2013 都拒绝此代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31504163/