C ++枚举类可以有方法吗?

我有一个枚举类有两个值,我想创build一个方法接收一个值,并返回另一个。 我也想维护types安全(这就是为什么我使用枚举类而不是枚举)。

http://www.cplusplus.com/doc/tutorial/other_data_types/没有提及任何方法但是,我的印象是,任何types的类都可以有方法。

不,C ++ enum不是一个类! 即使enum class (C ++ 11中的强types枚举)也不是类,尽pipe名称可能会引起误解。 我的教育猜测是关键字的select是由我们在C ++ 11之前使用的模式来获得范围的枚举:

 class Foo { public: enum {BAR, BAZ}; }; 

但是,这只是语法。 同样, enum class不是一个class

正如在其他答案中提到的,没有。 即使enum class是不是一个类。


通常需要有一个enum方法是因为它不是一个常规的 (只是递增的)枚举,而是一些按位定义的值被屏蔽或需要其他位算术运算:

 enum class Flags : unsigned char { Flag1 = 0x01 , // Bit #0 Flag2 = 0x02 , // Bit #1 Flag3 = 0x04 , // Bit #3 // aso ... } // Sets both lower bits unsigned char flags = (unsigned char)(Flags::Flag1 | Flags::Flag2); // Set Flag3 flags |= Flags::Flag3; // Reset Flag2 flags &= ~Flags::Flag2; 

很显然,人们认为通过例如位掩码值或者甚至位索引驱动的操作来封装重新设置单个/一组位的必要操作对于这样一组“标志”的操纵是有用的。

c ++ 11 struct / class 规范只是支持更好的访问枚举值范围。 没有更多,不less!

如何摆脱限制,你不能为enum(类)声明方法 ,要么使用std::bitset (包装类),要么使用位域union

union和这样的工会可以有办法(见这里的限制!)。

我有一个示例,如何将位掩码值(如上所示)转换为相应的位索引,可以在std::bitset : BitIndexConverter.hpp
我发现这对提高一些基于“标志”分辨率的algorithm的可读性非常有用。

专注于问题的描述,而不是标题,可能的答案是

 struct LowLevelMouseEvent { enum Enum { mouse_event_uninitialized = -2000000000, // generate crash if try to use it uninitialized. mouse_event_unknown = 0, mouse_event_unimplemented, mouse_event_unnecessary, mouse_event_move, mouse_event_left_down, mouse_event_left_up, mouse_event_right_down, mouse_event_right_up, mouse_event_middle_down, mouse_event_middle_up, mouse_event_wheel }; static const char* ToStr (const type::LowLevelMouseEvent::Enum& event) { switch (event) { case mouse_event_unknown: return "unknown"; case mouse_event_unimplemented: return "unimplemented"; case mouse_event_unnecessary: return "unnecessary"; case mouse_event_move: return "move"; case mouse_event_left_down: return "left down"; case mouse_event_left_up: return "left up"; case mouse_event_right_down: return "right down"; case mouse_event_right_up: return "right up"; case mouse_event_middle_down: return "middle down"; case mouse_event_middle_up: return "middle up"; case mouse_event_wheel: return "wheel"; default: Assert (false); break; } return ""; } };