枚举变量默认值? [英] Enum variable default value?
问题描述
问题很简单:
#include <iostream>
enum SomeEnum {
EValue1 = 1,
EValue2 = 4
};
int main() {
SomeEnum enummy;
std::cout << (int)enummy;
}
输出是什么?
注意:这是不面试,这是我以前开发人员继承的代码。这里的流式运算符只是例子,实际的继承代码没有。
Note: This is not an interview, this is code inherited by me from previous developers. Streaming operator here is just for example, actual inherited code doesn't have it.
推荐答案
程序有未定义行为。枚举的价值是不确定的。从概念上讲,您的代码与以下代码之间没有区别:
The program has Undefined Behavior. The value of enummy is indeterminate. Conceptually there is no difference between your code and the following code:
int main() {
int i; //indeterminate value
std::cout << i; //undefined behavior
};
如果您已经在名称空间范围内定义了变量,那么它将被初始化为0。 >
If you had defined your variable at namespace scope, it would be value initialized to 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
}
不要惊讶, e
可以具有与 SomeEnum
的枚举值的任何值不同的值。每个枚举类型都有一个基本的整数类型(例如 int
, short
或 long
),并且该枚举类型的对象的可能值的集合是底层积分类型具有的值集合。枚举只是方便地命名一些值并创建一个新类型的方式,但是您不要通过枚举器值的值来限制枚举的值。
Don't be surprised that e
can 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.
更新: 有些引号支持我:
Update: Some quotes backing me:
要零初始化类型T的对象意味着:
- 如果T是标量类型(3.9),则将对象设置为转换为T的0
(零)值;
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;
请注意,枚举是标量类型。
Note that enumerations are scalar types.
要初始化一个类型T的对象意味着:
- 如果T是类类型
blah blah
- 如果T是非工会类
类型blah blah
- 如果T是数组类型,那么blah blah -
否则,该对象为零初始化
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
所以,我们进入其他部分。而命名空间范围对象是值初始化的
So, we get into otherwise part. And namespace-scope objects are value-initialized
这篇关于枚举变量默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!