众所周知,静态数据成员不得在类定义中定义:
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; }
在这个例子中,所有的枚举数都是在类范围内声明的,实际上:
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/