0

我有一个具有 3 个值的枚举:

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
}

我错过了什么吗?

4

2 回答 2

1

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

(1 == (1 || 2))

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

同样的事情也会发生

(1 == (1 || 4))
(1 == (0 || 1))
(1 == (0 || 4))

他们都是真的。

(2 == (1 || 2))

是假的。

于 2013-04-07T21:16:28.543 回答
1

|| 是一个需要两个布尔值的二元运算。在您的示例中,布尔值是使用 == 测试相等性的结果。

要了解您的简化示例为何有效,让我们评估表达式

1 == (1 || 2)

We must start inside the parentheses first, so we are going to first evaluate (1 || 2). In C++, any non-zero value is equivalent to true when it is used in a boolean expression, so (1 || 2) is equivalent to (true || true) which evaluates to true. So now our expression is

1 == true

Again, 1 is equivalent to true in this context, so this comparison is the same as true == true, which of course evaluates to true.

于 2013-04-07T21:17:03.333 回答