您从使用枚举中获得了什么?使用位域、常量或#define。枚举不应用于位字段,因为您最终会得到不是有效枚举值的值。例如 LEFT|TOP 是 0x3 并且您没有将其作为枚举值。
还有很多其他方法可以做到这一点。有些人对哪个有偏好。
#define GBR_LEFT (1U << 0U)
#define GBR_TOP (1U << 1U)
#define GBR_RIGHT (1U << 2U)
#define GBR_BOTTOM (1U << 3U)
#define GBR_MASK_ALL (GBR_LEFT | GBR_TOP | GBR_RIGHT | GBR_BOTTOM)
或者
static const unsigned int GBR_LEFT = (1U << 0U);
static const unsigned int GBR_TOP = (1U << 1U);
static const unsigned int GBR_RIGHT = (1U << 2U);
static const unsigned int GBR_BOTTOM = (1U << 3U);
static const unsigned int GBR_MASK_ALL = (GBR_LEFT | GBR_TOP | GBR_RIGHT | GBR_BOTTOM);
或者最好使用位域(尽管如果您要定义实际的硬件寄存器或编译器永远无法破坏的东西,则永远不要这样做)
struct gbrLocation
{
unsigned left :1;
unsigned top :1;
unsigned right :1;
unsigned bottom :1;
};
通常设置清晰的掩码也是明智的,这样您就不必在很多括号内嵌套位反转。这有助于提高代码的可读性。