考虑以下(简化的)代码:
enum eTestMode
{
TM_BASIC = 1, // 1 << 0
TM_ADV_1 = 1 << 1,
TM_ADV_2 = 1 << 2
};
...
int m_iTestMode; // a "bit field"
bool isSet( eTestMode tsm )
{
return ( (m_iTestMode & tsm) == tsm );
}
void setTestMode( eTestMode tsm )
{
m_iTestMode |= tsm;
}
这是可靠、安全和/或良好的做法吗?或者除了使用 const int 而不是枚举之外,是否有更好的方法来实现我想做的事情?我真的更喜欢枚举,但代码可靠性比可读性更重要。
最佳答案
我看不出那个设计有什么不好。
但是,请记住 enum
类型可以包含未指定的值。根据谁使用您的函数,您可能需要先检查 tsm
的值是否是有效的枚举值。
因为 enums
是整数值,所以可以这样做:
eTestMode tsm = static_cast<eTestMode>(17); // We consider here that 17 is not a valid value for your enumeration.
但是,这样做很丑陋,您可能只是认为这样做会导致未定义的行为。
关于c++ - 在 C++ 中使用枚举进行面向整数位的操作是否可靠/安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3148850/