C++ 枚举变量默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6842799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:45:30  来源:igfitidea点击:

Enum variable default value?

c++variablesenumsdefault-value

提问by Haspemulator

The question is simple:

问题很简单:

#include <iostream>

enum SomeEnum {  
    EValue1 = 1,  
    EValue2 = 4
};

int main() {
    SomeEnum enummy;
    std::cout << (int)enummy;
}

What will be the output?

输出会是什么?

Note: This is notan interview, this is code inherited by me from previous developers. Streaming operator here is just for example, actual inherited code doesn't have it.

注意:这不是采访,这是我从以前的开发人员那里继承的代码。这里的流操作符只是举例,实际继承的代码没有它。

采纳答案by Armen Tsirunyan

The program has Undefined Behavior. The value of enummy is indeterminate. Conceptually there is no difference between your code and the following code:

该程序具有未定义的行为。enum 的值是不确定的。从概念上讲,您的代码与以下代码没有区别:

int main() {
   int i;          //indeterminate value
   std::cout << i; //undefined behavior
};

If you had defined your variable at namespace scope, it would be value initialized to 0.

如果您在命名空间范围内定义了变量,则它的值将被初始化为 0。

enum SomeEnum {  
    EValue1 = 1,  
    EValue2 = 4,  
};
SomeEnum e; // e is 0
int i;      // i is 0

int main()
{
    cout << e << " " << i; //prints 0 0 
}

Don't be surprised that ecan have values different from any of SomeEnum's enumerator values. Each enumeration type has an underlying integral type(such as int, short, or long) and the set of possible values of an object of that enumeration type is the set of values that the underlying integral type has. Enum is just a way to conveniently name some of the values and create a new type, but you don't restrict the values of your enumeration by the set of the enumerators' values.

不要对e可以具有与任何SomeEnum枚举值不同的值感到惊讶。每个枚举类型都有一个基础整数类型(例如intshort、 或long),并且该枚举类型的对象的可能值集是基础整数类型具有的值集。枚举只是一种方便地命名某些值并创建新类型的方法,但您不会通过枚举器的值集来限制枚举的值。

Update:Some quotes backing me:

更新:一些支持我的报价:

To zero-initialize an object of type T means:
— if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T;

对 T 类型的对象进行零初始化意味着:
— 如果 T 是标量类型 (3.9),则将该对象设置为转换为 T 的 0(零)值;

Note that enumerations are scalar types.

请注意,枚举是标量类型。

To value-initialize an object of type T means:
— if T is a class type blah blah
— if T is a non-union class type blah blah
— if T is an array type, then blah blah — otherwise, the object is zero-initialized

对类型 T 的对象进行值初始化意味着:
— 如果 T 是类类型等等
— 如果 T 是非联合类类型等等
— 如果 T 是数组类型,则等等 — 否则,对象为零-初始化

So, we get into otherwise part. And namespace-scope objects are value-initialized

所以,我们进入其他部分。并且命名空间范围的对象是值初始化的