我一直在查看来自开源项目的一些代码,并注意到在不止一次的情况下,枚举的值是通过将值移位一个递增的位置来分配的。我看不到这样做的任何具体原因,也看不到仅通过增加 +1 来分配值的效率有所提高。
无论如何,如果没有一些代码来证明让我感到困惑的事情,这可能毫无意义。
1级
enum EventType {
NONE = 0,
PUSH = 1<<0,
RELEASE = 1<<1,
DOUBLECLICK = 1<<2,
DRAG = 1<<3,
MOVE = 1<<4,
KEYDOWN = 1<<5,
KEYUP = 1<<6,
FRAME = 1<<7,
RESIZE = 1<<8,
SCROLL = 1<<9,
PEN_PRESSURE = 1<<10,
PEN_ORIENTATION = 1<<11,
PEN_PROXIMITY_ENTER = 1<<12,
PEN_PROXIMITY_LEAVE = 1<<13,
CLOSE_WINDOW = 1<<14,
QUIT_APPLICATION = 1<<15,
USER = 1<<16
};
2 级
enum EventType {
EVENT_MOUSE_DOUBLE_CLICK = osgGA::GUIEventAdapter::DOUBLECLICK,
EVENT_MOUSE_DRAG = osgGA::GUIEventAdapter::DRAG,
EVENT_KEY_DOWN = osgGA::GUIEventAdapter::KEYDOWN,
EVENT_SCROLL = osgGA::GUIEventAdapter::SCROLL,
EVENT_MOUSE_CLICK = osgGA::GUIEventAdapter::USER << 1,
EVENT_MULTI_DRAG = osgGA::GUIEventAdapter::USER << 2, // drag with 2 fingers
EVENT_MULTI_PINCH = osgGA::GUIEventAdapter::USER << 3, // pinch with 2 fingers
EVENT_MULTI_TWIST = osgGA::GUIEventAdapter::USER << 4 // drag 2 fingers in different directions
};
如果我没看错,EventType::USER 的二进制显式值为 65536 或 10000000000000000。EVENT_MULTI_TWIST 的二进制值为 1048576 或 100000000000000000000。
以这种方式分配枚举值的目的是什么,而不是像这样:
enum EventType {
NONE = 0,
PUSH = 1,
RELEASE = 2,
DOUBLECLICK = 3,
DRAG = 4,
MOVE = 5,
KEYDOWN = 6,
KEYUP = 7,
FRAME = 8,
RESIZE = 9,
SCROLL = 10,
PEN_PRESSURE = 11,
PEN_ORIENTATION = 12,
PEN_PROXIMITY_ENTER = 13,
PEN_PROXIMITY_LEAVE = 14,
CLOSE_WINDOW = 15,
QUIT_APPLICATION = 16,
USER = 17
};