【发布时间】:2012-07-10 09:48:31
【问题描述】:
如何在 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
【问题讨论】:
-
为什么要输出枚举? enum 类用于不将枚举值与 int 表示混淆
-
@RiaD 如果您在 switch 语句中评估枚举类值并希望在默认分支中捕获未处理的值怎么办,例如打印未处理的值?
-
@stackprotector 好吧,在过去的 9 年里,我学到了一些需要它的用例 :) 当然,你的用例是其中的主要部分
标签: c++ c++11 templates enums enum-class