2013-04-07 76 views
0

我有3个值的枚举:C++枚举和OR条件

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 == (1 || 2) 

首先,我们必须在括号内启动,所以我们将首先评估(1 || 2)。在C++中,任何非零值在布尔表达式中使用时相当于true,所以(1 || 2)相当于(true || true),其值为true。所以,现在我们的表现是

1 == true 

再次,1相当于在此背景下true,所以这种比较是一样的true == true,这当然计算结果为true

1

是的,你错过了一些东西。这个工作总事故:

(1 == (1 || 2)) 

它没有设置比较。它只是将(1 || 2)计算为true,然后将其转换为其整数值(1),即true

同样的事情会发生与

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

,他们都属实。

(2 == (1 || 2)) 

是假的。