c++ - 类定义中的无作用域枚举数

标签 c++ class enums nested

众所周知,静态数据成员不得在类定义中定义:

N4296:9.4.2/2 [class.static.data]

The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition.

考虑以下类:

#include <iostream>

struct A
{
    enum E { x = 2, y = 3 }; //both enuerators are defined in the definition of `A`
};

int x = A::x; //looks like A::x is static data member, despite being defined in the scope of `A`

int main(){ std::cout << x << std::endl; }

DEMO

在这个例子中,所有的枚举数都是在类范围内声明的,实际上:

N4296::7.2/11 [dcl.enum]

Each enum-name and each unscoped enumerator is declared in the scope that immediately contains the enum-specifier.

因此,尚不清楚无作用域枚举器是静态数据成员还是非静态数据成员。我们可以在 object-expression 之外使用它们,因此它们应该是静态的。另一方面,我们不能在类范围内定义静态数据成员。我觉得这有点矛盾,你不能澄清一下吗?

最佳答案

在您的示例中,A::x 根本不是数据成员。它没有存储空间。要向自己证明这一点,请尝试获取其地址:你不能。

关于c++ - 类定义中的无作用域枚举数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27699714/

相关文章:

c++ - 如何迭代一个int数组?

c++ - 如何告诉 ld 在哪里可以找到 libc

c++ - 在 C++17 中使用容器时,noexcept move 操作是否有好处?

python - 为什么在类级别使用列表压缩时会引发 NameError?

c++ - 如何在 C++ 中实现枚举

ios - 快速枚举类

c# - 如何获取枚举在其定义列表中的数字位置?

c++ - 未找到 libpng "png_set_longjmp_fn"

c++ - 将局部变量作为 vector 的成员传递给被调用者

javascript - 如何在 Node 中导出类实例?