c++中的Enum和OR条件
C++, Enum and OR condition
我有一个有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))
是假的。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- MongoDB 使用数组中的 OR 条件构建查询
- C++ if 语句将条件设置为 true 和循环中的 OR-ing 条件之间的行为差异
- 带有逻辑 OR 运算符的 if 条件的缩写?
- 虽然具有多个 OR 条件的循环不退出循环
- C++中的堆栈:切换"or"条件时出现运行时错误
- 如何处理 IF 中的多个 OR 条件
- 如果带有 OR 检查所有条件,则为条件
- 为什么我的 OR 条件检查匹配项的字符串总是返回 true
- C++:for 循环中的多个退出条件(多个变量):AND -ed 或 OR -ed
- if语句在有两个OR选项的第三个条件下不起作用
- 在or条件语句中是否存在强制对两个表达式求值的模式或技巧?
- IF语句中的多个OR或AND条件
- c++中的Enum和OR条件
- gcc 或其他编译器在条件表达式中使用时是否会自动将按位 or 转换为布尔值 or?