c++ - C++语法 “A::B:A {};”是什么意思

标签 c++ struct syntax scope-resolution

C++ 语法 struct A::B:A {}; 是什么意思? C++ 标准中描述的这个名称定义(或访问)在哪里?

#include <iostream>

struct B;

struct A {
    struct B;
};

struct A::B:A {
};

int main() {
    A::B::A::B b;
    std::cout<<"Sizeof A::B::A::B is " << sizeof(A::B::A::B)<<std::endl;
    return 0;
}

最佳答案

这个定义

struct A {
    struct B;
};

使用嵌套结构 B1 的声明定义结构 AB 的完全限定名称是 A::B,你可以说 BA。那么这个:

struct A::B : A { // Note I added spaces
};

A::B的定义,单个:指定是派生A.

现在,有趣的部分是 A::B::A::B。让我们剖析一下:

  1. A::B 命名嵌套结构。
  2. A::B::A 访问B 中注入(inject)的类名A。注入(inject)是由于继承。
  3. A::B::A::B 再次将A 中的嵌套结构B 命名。

您可以无限继续,或者至少直到您的编译器达到其翻译限制2

一个有趣的智力练习,但避免像实际代码中的瘟疫一样。


[class.qual]/1解释查找的工作原理

If the nested-name-specifier of a qualified-id nominates a class, the name specified after the nested-name-specifier is looked up in the scope of the class ([class.member.lookup]), except for the cases listed below. The name shall represent one or more members of that class or of one of its base classes (Clause [class.derived]).

上面的文本允许我们命名基类,因为 [class]/2

The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name. For purposes of access checking, the injected-class-name is treated as if it were a public member name.

上面清楚地表明,以 A:: 开头的完全限定名称允许您指定成员或基类。由于 A 没有基数,您只能指定 A::B (“成员类型”)。但是 A::B 也指定了一个类。所以我们也可以用 A::B:: 来指定 that 的基类或成员,它允许我们命名 A::B::A。现在冲洗并重复。


<子> 1 - 注意它是一个完全不同的 B。与全局 struct B 完全无关。
2 - 根据 [implimits]/2.36 建议的最小值为 256

关于c++ - C++语法 “A::B:A {};”是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47546616/

相关文章:

c++ - 关于缩放 QGraphicsView/QGraphicsScene 的一般建议

c - 这就是我在链表中​​创建链表的方式吗?

arrays - 结构数组 : How to save in coredata?

c - 如何通过强制转换使用通用结构来访问具有相同第一个元素的多个结构

python - 是否可以转义 Python 中的保留字?

c - 检查相邻数组的简单方法

c++ - MFC 自定义 Tab 键事件处理程序

c++ - 为什么我必须为文件末尾的 seekg 提供负两个偏移量

c++ - OpenGL 离屏渲染和使用 glfw 的隐藏窗口读取像素值

haskell - Haskell 中的多个语句