gpt4 book ai didi

c++ - 在 C++ 中通过 int 将枚举转换为枚举

转载 作者:太空狗 更新时间:2023-10-29 21:19:24 33 4
gpt4 key购买 nike

通过 int 转换将枚举转换为不同的枚举是否有效,如下图所示?看起来 x64 的 gcc 没有问题,但其他编译器和平台也有问题吗?

a 等于 A_third 并且在 enum_B 中没有等价物时会发生什么?

enum enum_A {
A_first = 0,
A_second,
A_third
};

enum enum_B {
B_first = 0,
B_second
};

enum_A a = A_first;
enum_B b;

b = enum_B(int(a));

最佳答案

由于某些边缘情况,您在执行此操作时必须小心:

来自 C++11 标准(§7.2,6):

For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int.

这意味着 enum 可能是比 int 更大的类型,因此从 enumint 的转换 可能会失败并产生未定义的结果。

根据上述内容,可以int 转换为 enum,从而产生 的枚举器值enum 没有明确指定。通俗地讲,您可以将 enum 视为具有一些用标签明确定义的值的整数类型。

关于c++ - 在 C++ 中通过 int 将枚举转换为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27442863/

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