什么是C ++中默认初始化的全局强类型枚举? [英] What are global strongly-typed enums initialized to by default in C++?
问题描述
我正在尝试确定初始化全局强类型枚举的默认值。以下代码当然不能编译。
I'm trying to determine the default value to which global strongly-type enums are initialized. The following code of course does not compile.
#include <iostream>
using namespace std;
enum class A{a=10, b=20};
// Global strongly-typed enum, uninitialized
A k;
int main() {
if(k==A::a)
cout<<"Equal to a"<<endl;
else if(k==A::b)
cout<<"Equal to b"<<endl;
else if(k==0)
cout<<"Equal to zero"<<endl;
return 0;
}
什么是k初始化?
推荐答案
k
具有静态存储持续时间和静态对象为零初始化,我们可以看到 C ++标准草案部分 3.6.2
初始化非局部变量段落 2 :
k
has static storage duration and static objects are zero initialized, we can see this by going to the draft C++ standard section 3.6.2
Initialization of non-local variables paragraph 2:
在任何其他
初始化发生之前,具有静态存储持续时间(3.7.1)或线程存储
持续时间(3.7.2)的变量应为零初始化(8.5)。 [...]
Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place. [...]
用于标量类型,意味着初始化为零,其中包含部分 8.5
段落 6 其中说:
for scalar types that means initialization to zero, which is covered section 8.5
paragraph 6 which says:
要初始化一个对象或类型T的对象意思是:
To zero-initialize an object or reference of type T means:
,并包含以下项目符号:
and includes the following bullet:
如果T是标量类型(3.9),则将对象初始化为通过将整数文字0(零)转换为T而获得的值
; 105
if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;105
我们知道一个枚举是从 3.9
类型段落 9 它说:
we know an enum is a scalar type from section 3.9
Types paragraph 9 which says:
算术类型(3.9.1),枚举类型,指针类型,指向
成员类型的指针3.9.2),std :: nullptr_t和cv-qualified版本的
这些类型(3.9.3)被统称为标量类型[...]
Arithmetic types (3.9.1), enumeration types, pointer types, pointer to member types (3.9.2), std::nullptr_- t, and cv-qualified versions of these types (3.9.3) are collectively called scalar types.[...]
零
是一个有效的值,因为un枚举类型可以包含其值和部分 7.2
枚举声明段落 8 表示枚举可以取值未定义通过枚举器:
zero
is a valid value since the underlying type can contain its value and section 7.2
Enumeration declarations paragraph 8 says that an enumeration can take a value not defined by its enumerators:
[...]可以定义一个枚举值不是由
定义的任何其枚举器。[...]
[...]It is possible to define an enumeration that has values not defined by any of its enumerators.[...]
这篇关于什么是C ++中默认初始化的全局强类型枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!