在 C++ 中,嵌套类有权访问封闭类的所有成员。这是否也适用于嵌套类的嵌套类?
这段代码
#include <iostream>
class A
{
public:
class B
{
public:
B() { std::cout << A::x << std::endl; }
class C
{
public:
C() { std::cout << A::x << std::endl; }
};
};
private:
static const int x { 0 };
};
int main()
{
A::B b;
A::B::C c;
}
在 g++ 7.2 上编译时没有警告。但是,我不清楚这是否符合标准。标准草案 (N4727 14.7) 说:
A nested class is a member and as such has the same access rights as any other member.
但是,在上面的例子中,C
不是A
的成员,它是成员的成员。这里的标准模棱两可吗? g++ 行为是否可移植?
最佳答案
However, in the example above
C
is not a member ofA
, it is a member of a member.
是的,这是明确定义的行为;访问权限从 B
转移。
根据标准[class.access]/2 ,
A member of a class can also access all the names to which the class has access.
Members of a class are data members, member functions, nested types, enumerators, and member templates and specializations thereof.
C
是B
的嵌套类,也是B
的成员,那么C
可以访问命名 B
可以访问的内容,包括 A::x
。同理,C::C
是C
的成员,它可以访问C
可以访问的名字,所以访问
没问题。C::C
中的 >A::x
关于c++ - 嵌套类的嵌套类的访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49585664/