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

标签 c++ enums

<分区>

以下是我的测试代码

#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;
}

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

最佳答案

n3376 5.2.9/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).

关于c++ - 需要 C++ 中的枚举类型转换解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28477393/

相关文章:

c++ - 什么是C++运行时概念?

c++ - Boost Asio - 如何知道处理程序队列何时为空?

具有 ENUM 的 MAX() 值的 MYSQL JOIN

python - 如何在字典中的枚举中添加文档字符串

c - 如何将一个枚举的元素映射到另一个枚举的元素?

java - 在Spring Boot应用程序中从Enums动态创建列

c++ - 确定代码是否在特定线程中运行

c++ - 使用 Intel archiver 命令而不是 ar 的 boost-build(又名 bjam)

c++ - 创建表达式的实现建议,稍后用于评估 c++ 中映射的内容?

java - 我不断收到的类、接口(interface)或枚举错误是什么