gpt4 book ai didi

c++ - 枚举变量默认值?

转载 作者:IT老高 更新时间:2023-10-28 13:24:25 30 4
gpt4 key购买 nike

问题很简单:

#include <iostream>

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

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

输出会是什么?

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

最佳答案

该程序有 Undefined Behavior . enummy 的值是不确定的。从概念上讲,您的代码与以下代码没有区别:

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

如果你在命名空间范围内定义了你的变量,它的值将被初始化为 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 的任何枚举值,请不要感到惊讶。每个枚举类型都有一个底层整数类型(例如 intshortlong)以及该对象的可能值集枚举类型是基础整数类型具有的一组值。枚举只是一种方便地命名一些值并创建新类型的方法,但您不会通过枚举器值的集合来限制枚举的值。

更新: 支持我的一些引用:

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;

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

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

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

关于c++ - 枚举变量默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6842799/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com