需要 C++ 中的枚举类型转换解释

Need enum type casting explanation in c++

以下是我的测试代码

#include "test.h"
#include <iostream>

typedef enum{
    A = 0,
    B
 } testEnum;

int main()
{
    testEnum e = static_cast<testEnum>(3);
    printf("My enum Value : %d\n", (int)e);
    int stop = 0;
}

节目出来是My enum Value : 3 现在在程序中,我将数字 3 键入 enum,然后将其打印为 int。我猜这应该给出错误或垃圾值或 1(作为枚举最高值)。但是输出是 3。有人可以知道规则是什么以及它是如何工作的。谢谢!

整数类型的枚举(数字)。通过类型转换,您告诉编译器您知道该值是正确的,但没有发生转换。 values/range 需要你自己检查。

顺便说一句。它实际上给出了一个垃圾值:3

Naht Kh.A.p./10

A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting value is unspecified (and might not be in that range).