3 回答

TA貢獻1811條經驗 獲得超4個贊
“正確”的方法是為枚舉定義位運算符,如:
enum AnimalFlags{ HasClaws = 1, CanFly =2, EatsFish = 4, Endangered = 8};inline AnimalFlags operator|(AnimalFlags a, AnimalFlags b){return static_cast<AnimalFlags>(static_cast<int>(a) | static_cast<int>(b));}
等等其他位運算符。如果枚舉范圍超出int范圍,則根據需要進行修改。

TA貢獻1842條經驗 獲得超13個贊
注意(也有點偏離主題):使用位移可以完成另一種制作唯一標志的方法。我,我自己,發現這更容易閱讀。
enum Flags{ A = 1 << 0, // binary 0001 B = 1 << 1, // binary 0010 C = 1 << 2, // binary 0100 D = 1 << 3, // binary 1000};
它可以將值保持為int,因此在大多數情況下,32個標志清楚地反映在移位量中。

TA貢獻1828條經驗 獲得超4個贊
對于像我這樣的懶人,這里是復制和粘貼的模板化解決方案:
template<class T> inline T operator~ (T a) { return (T)~(int)a; }
template<class T> inline T operator| (T a, T b) { return (T)((int)a | (int)b); }
template<class T> inline T operator& (T a, T b) { return (T)((int)a & (int)b); }
template<class T> inline T operator^ (T a, T b) { return (T)((int)a ^ (int)b); }
template<class T> inline T& operator|= (T& a, T b) { return (T&)((int&)a |= (int)b); }
template<class T> inline T& operator&= (T& a, T b) { return (T&)((int&)a &= (int)b); }
template<class T> inline T& operator^= (T& a, T b) { return (T&)((int&)a ^= (int)b); }
- 3 回答
- 0 關注
- 573 瀏覽
添加回答
舉報