如何在 C++11 中输出 enum class
的值?在 C++03 中是这样的:
#include <iostream>
using namespace std;
enum A {
a = 1,
b = 69,
c= 666
};
int main () {
A a = A::c;
cout << a << endl;
}
在 c++0x 中,此代码无法编译
#include <iostream>
using namespace std;
enum class A {
a = 1,
b = 69,
c= 666
};
int main () {
A a = A::c;
cout << a << endl;
}
prog.cpp:13:11: error: cannot bind 'std::ostream' lvalue to 'std::basic_ostream<char>&&'
/usr/lib/gcc/i686-pc-linux-gnu/4.5.1/../../../../include/c++/4.5.1/ostream:579:5: error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char, _Traits = std::char_traits<char>, _Tp = A]'
在 Ideone.com 编译
原文由 Adi 发布,翻译遵循 CC BY-SA 4.0 许可协议
与无范围枚举不同,有范围枚举不能 隐式 转换为其整数值。您需要使用强制转换将其 显式 转换为整数:
您可能希望将逻辑封装到函数模板中:
用作: