我在测试时遇到了这个问题。
我知道我可以做类似的事情:
enum class Color { red, green = 1, blue };
Color c = Color::blue;
if( c == Color::blue )
cout << "blue\n";
但是当我用cout << "blue\n";
替换cout << Color::green
时,它甚至无法编译。为什么不编译?
答案 0 :(得分:5)
发生此错误是因为C ++没有预先定义的打印enum
的方法。您需要定义一个运算符<<
,以根据您的需要打印Color
枚举类型的对象。
例如,如果您要打印数值,请将颜色转换为运算符内的int
:
ostream& operator<<(ostream& ostr, const Color& c) {
ostr << (int)c;
return ostr;
}
如果您想将enum
值打印为文字see this Q&A for a sample implementation。