嵌套 class 的嵌套 class 的访问权限

Access rights of a nested class of a nested class

在 C++ 中,嵌套的 class 有权访问封闭 class 的所有成员。这是否也适用于嵌套 class 的嵌套 class?

这个代码

#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 of A, it is a member of a member.

是的,这是 well-defined 行为;访问权限从 B.

转移

按照标准[class.access]/2,

A member of a class can also access all the names to which the class has access.

[class.mem]/1,

Members of a class are data members, member functions, nested types, enumerators, and member templates and specializations thereof.

CB的嵌套class,也是B的成员,那么C可以访问什么名字B 可以访问,包括 A::x。同理,C::CC的成员,它可以访问C可以访问的名称,所以访问C::C中的A::x是可以的。

行为是 well-defined 和 in-line 的标准措辞。你缺少的是 [class.access]p2 的相关措辞,它加强了你已经引用的内容:

A member of a class can also access all the names to which the class has access. A local class of a member function may access the same names that the member function itself may access.

这意味着可访问性是可传递的。如果 C 可以访问与 B 相同的实体,这也意味着 C 可以访问 A 中的实体,因为 B 可以访问它们.

class A {
  class B {
    class C {
      C() { A::x; /* well-defined */ }
    };
  };

  static int x;
};