我是否正确地将枚举值与C ++的“或”运算符进行比较?

时间:2013-09-22 00:52:31

标签: c++ enums

我编写了一段似乎不能按要求运行的代码:

typedef enum{none=0,apple,grape,orange} FRUIT;

FRUIT first = rand()%4;
FRUIT second = rand()%4;
FRUIT third = rand()%4;

所以在我的if条件下,我能否

if (first == (none | apple | grape | orange) &&
    second == apple &&
    third == (none | apple | grape | orange)
{
    cout<<"Here"<<<endl;
}

变量firstthird可以包含任何 apple grape none 橙色值。 if条件是否正确?我没有得到所需的输出,因为它根本没有输入if条件。

2 个答案:

答案 0 :(得分:3)

条件:

first == (none | apple | grape | orange)

您应该使用逻辑或(||)而不是按位或(|)。不幸的是,即使您将其更改为:

first == (none || apple || grape || orange)

首先评估此条件的右侧,使其(在本例中)等效于:

first == true

仍然与你的意思在语义上不同:

first == none || first == apple || first == grape || first == orange

另请注意,使用rand()并不是很明智。您可以尝试使用std::random_shuffle代替:

FRUIT fruit[] = { none, apple, grape, orange,
                  none, apple, grape, orange,
                  none, apple, grape, orange};
srand(time(NULL));
std::random_shuffle(&fruit[0], &fruit[11]);
FRUIT first = fruit[0];
FRUIT second = fruit[1];
FRUIT third = fruit[2];

不要忘记#include <algorithm>:)

答案 1 :(得分:0)

  

我是否正确地将枚举值与C ++的“或”运算符进行比较?

没有。你需要写:

first == none || first == apple || first == grape || first == orange