3 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
“正確”的方法是為枚舉定義位運(yùn)算符,如:
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));}
等等其他位運(yùn)算符。如果枚舉范圍超出int范圍,則根據(jù)需要進(jìn)行修改。

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

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
對于像我這樣的懶人,這里是復(fù)制和粘貼的模板化解決方案:
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 關(guān)注
- 562 瀏覽
添加回答
舉報(bào)