簡體   English   中英

我是否將枚舉值與C ++的“或”運算符正確比較?

[英]Am I comparing enum values with C++'s “or” operator correctly?

我寫了一段似乎無法按要求工作的代碼:

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

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

所以在我的情況下,我可以

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

變量firstthird可以具有applegrapenoneorange值中的任何一個 那么條件是否正確? 我沒有得到所需的輸出,因為它根本沒有輸入if條件。

條件:

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> :)

我是否將枚舉值與C ++的“或”運算符正確比較?

否。您需要寫:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM