c++ - 无法使用 static_cast 将枚举类转换为 int

标签 c++ gcc c++11 enums

enum class TestEnum : int
{
    first,
    second
};

int main()
{
    int n = static_cast<int>(TestEnum::second);   // error
    return 0;
}

构建日志:

g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++0x -MMD -MP -MF"src/test.d" -MT"src/test.d" -o "src/test.o" "../src/test.cpp"
../src/test.cpp: In function ‘int main()’:
../src/test.cpp:20:20: error: cannot convert ‘TestEnum’ to ‘int’ in initialization

海湾合作委员会版本 4.6.3

如何将 enum class 实例转换为 int

最佳答案

您正在尝试使用 -std=c++0x 键编译您的代码。但是强类型枚举enum class是C++11的特性,所以你最好使用更新的GCC编译器。 GCC 4.7 或更高版本是合适的,它有 -std=c++11 命令行键:http://gcc.gnu.org/projects/cxx0x.html

此代码有效:http://ideone.com/4IQPUx

关于c++ - 无法使用 static_cast 将枚举类转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20773898/

相关文章:

c++ std::string 到 bool 值

c++ - 基于栈的虚拟机函数调用/返回实现问题

c++ - 从容器中提取段的函数

c++ - 嵌套 for 循环和重复迭代器

c++ - 前向声明导致VC++错误,不知道如何解决

c - GCC 和 VC++ 中的宏

c - Mageia-Linux x86_64 错误 : exec shell C code with static compilation

c++ - 为什么 C++11 constexpr 如此严格?

c# - 在 .NET 进程中观看本地进程创建的全局事件

c - 参数长度可变的宏