c++中的Enum和OR条件

C++, Enum and OR condition

本文关键字:OR 条件 Enum 中的 c++      更新时间:2023-10-16

我有一个有3个值的enum:

enum InputState { Pressed, Released, Held };

我在这段代码中使用它:

//GetState returns an InputState
if(myInput.GetState(keyCode) == InputState::Pressed)
{
    //This means "keyCode" has the state "Pressed"
}

为什么这个不行?

if(myInput.GetState(keyCode) == (InputState::Pressed || InputState::Held))
{
    //This is always false
}
if((myInput.GetState(keyCode) == InputState::Pressed) || (myInput.GetState(keyCode) == InputState::Held))
{
    //This works as intended, triggers when "keyCode" is either Pressed OR Held
}

作为测试,我做了:

//Using the same values from the enum, but as int now
if(1 == (1 || 2))
{
    //This works as intended
}

我错过了什么吗?

||是一个二元操作,需要两个布尔值。在您的示例中,布尔值是测试与==是否相等的结果。

要了解为什么您的简化示例可以工作,让我们计算表达式

1 == (1 || 2)

我们必须先从括号内开始,所以我们要先计算(1 || 2)。在c++中,任何非零值在布尔表达式中使用时都相当于true,因此(1 || 2)相当于(true || true),其计算结果为true。现在我们的表达式是

1 == true

同样,1在此上下文中相当于true,因此此比较与true == true相同,其计算结果当然是true

是的,你错过了一些东西。这完全是意外:

(1 == (1 || 2))

不是集合比较。它简单地将(1 || 2)计算为true,然后将true转换为其整数值(1)。

也会发生同样的事情
(1 == (1 || 4))
(1 == (0 || 1))
(1 == (0 || 4))

它们都是真的

,

(2 == (1 || 2))

是假的。