开发者

Overload output operator in a enum in C++

开发者 https://www.devze.com 2023-02-18 09:27 出处:网络
Its posible to overload th开发者_StackOverflow中文版e output operator inside an enum ? I\'m getting all sort of errors(if I use class, I dont get any):

Its posible to overload th开发者_StackOverflow中文版e output operator inside an enum ? I'm getting all sort of errors(if I use class, I dont get any):

   ../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

I'm after to implement something like this(java code):

public enum Type { 

  ACOUSTIC, ELECTRIC;

  public String toString() {
    switch(this) {
      case ACOUSTIC: return "acoustic";
      case ELECTRIC: return "electric";
      default:       return "unspecified";
    }
  }
}

Thank you.

edit:

enum Type {
    //ACOUSTIC, ELECTRIC;
    inline std::ostream& operator << (std::ostream& os, Type t) // error here
    {

    }
};


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消