它可以在枚举中重载输出操作符吗?我遇到了各种错误(如果我使用课程,我没有得到任何错误):
../src/oop.cpp:18:2: error: expected identifier before 'friend'
../src/oop.cpp:18:2: error: expected '}' before 'friend'
../src/oop.cpp:18:2: error: 'friend' used outside of class
../src/oop.cpp:18:16: error: expected initializer before '&' token
../src/oop.cpp:22:1: error: expected declaration before '}' token
我要实现类似这样的东西(java代码):
public enum Type {
ACOUSTIC, ELECTRIC;
public String toString() {
switch(this) {
case ACOUSTIC: return "acoustic";
case ELECTRIC: return "electric";
default: return "unspecified";
}
}
}
谢谢。
编辑:
enum Type {
//ACOUSTIC, ELECTRIC;
inline std::ostream& operator << (std::ostream& os, Type t) // error here
{
}
};
答案 0 :(得分:5)
enum MyEnum {
foo, bar
};
inline std::ostream & operator<<(std::ostream & Str, MyEnum V) {
switch (V) {
case foo: return Str << "foo";
case bar: return Str << "bar";
default: return Str << (int) V;
}