c++ - 嵌套类的嵌套类的访问权限

标签 c++ language-lawyer inner-classes

在 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 of A, 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.

[class.mem]/1 ,

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

CB的嵌套类,也是B的成员,那么C可以访问命名 B 可以访问的内容,包括 A::x。同理,C::CC的成员,它可以访问C可以访问的名字,所以访问 C::C 中的 >A::x 没问题。

关于c++ - 嵌套类的嵌套类的访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49585664/

相关文章:

c++ - 使用C时间函数测量时间: are they code-reordering resistant?

c++ - 使用 const 成员放置 new 和类的赋值

java - 如何在 Proguard 中保留内部类的字段和方法(不仅是类本身)

c# - 防止从第三个外部类实例化在其外部类中使用的内部类

c++ - 在模板中排序链表 - 字符串问题

c++ - 在 shmget 中用作键的安全值

c++ - wxWidgets 和锁定资源

c++ - 在 C++ Set 和 Vector 中取消引用迭代器时出错

c++ - 对函数参数的要求是否也适用于初始化列表?

java - 从java中的内部类访问变量