【发布时间】:2019-10-08 19:38:46
【问题描述】:
我有以下示例代码。我一直认为对枚举值进行按位或运算可以让我检查结果(使用按位与)来查看结果中包含哪些枚举值,哪些不包含。
例如,如果我做result = mouse | headphone,那么我可以检查result & mouse == mouse 作为条件来知道mouse 是否包含在result 中。但似乎无论我 & 得到什么结果,比如 X,我总是以 X 结尾。为什么?
在下面的代码中,我认为 if 应该失败,因为 straw 不包含在 options 中,但它没有..
#include <iostream>
#include <iomanip>
using namespace std;
enum Stock
{
milk,
choclate,
tv,
cable,
mouse,
fan,
headphone,
cup,
straw,
pen,
candy,
glasses,
book,
plug
};
int main()
{
Stock options = static_cast<Stock>( static_cast<int>(mouse) | static_cast<int>(headphone)
| static_cast<int>(cup) | static_cast<int>(pen) );
if ((static_cast<int>(loptions)) & (static_cast<int>(straw)) == static_cast<int>(straw))
{
cout << "bring straw!" << endl;
}
system("PAUSE");
return 0;
}
编辑:
即使我为枚举值添加唯一位集,它也不起作用。对于下面的代码,当我期望它显示 "bring cup" 时,它会忽略这两个 if() 语句:
enum Stock
{
milk = 1,
choclate = 2,
tv = 4,
cable = 8,
mouse = 16,
fan = 32,
headphone = 64,
cup = 128,
straw = 256,
pen = 512,
candy = 1024,
glasses = 2048,
book = 4096,
plug = 8192
};
int main()
{
Stock options = static_cast<Stock>(static_cast<int>(mouse) | static_cast<int>(headphone)
| static_cast<int>(cup) | static_cast<int>(pen));
if ((static_cast<int>(options)) & (static_cast<int>(straw)) == static_cast<int>(straw))
{
cout << "bring straw!" << endl;
}
if ((static_cast<int>(options)) & (static_cast<int>(cup)) == static_cast<int>(cup))
{
cout << "bring cup!" << endl;
}
system("PAUSE");
return 0;
}
【问题讨论】:
-
您假设每个
enum的值都是唯一的位。事实并非如此。enums 的值总是比前一个枚举值高 1,除非另有规定。 -
@LambaDawet 是的,但唯一值并不意味着唯一不同的位。唯一位意味着需要使用值 1、2、4、8 等。例如
cable == tv | chocolate。milk为零,甚至没有任何位为 1。也许您对二进制 AND 和 OR 运算符的工作方式感到困惑。 -
要进行按位检查,不应该将不同的参数组合在一起(并用 AND 进行检查)都是 2 的幂(即 1,2,4,8,... ),而不是线性范围 0,1,2,3,4,5? (与@FrançoisAndrieux 的评论一致)
-
您的编辑中括号放错了。写
if ((options & cup) == cup)就够了,static_casts没用。但重要的是(options & cup) == cup而不是options & (cup == cup)
标签: c++ c++11 enums bitwise-operators