问题描述
让说我有布尔标志数组,将它设置为true或false取决于条件。
让说,指数1,2,6已定,其他所有标志都没有设置,我需要调用泛函
,如果指数2,3,5已设置和所有其他标志都没有设置,我需要调用 functionB
。有没有一种简单的方法,我可以执行上述逻辑以外做这样的:
如果(阵列[1] ==真&功放;&放大器;数组[2] ==真&功放;&放大器;数组[6] ==真&功放;&安培;
阵列[3] ==假放;&安培;数组[4] ==假放;&安培;阵列[5] == FALSE)
{
泛函();
}
维护和可读性的噩梦!
考虑这个:
布尔temperature_sensor_tripped(常量bool_array和放大器;标志)
{
的返回标志[1];
}
// [...]
如果(temperature_sensor_tripped(阵列)
&功放;&安培; moisture_sensor_tripped(阵列)
&功放;&安培; !alarm_dispatched(阵列))
{
泛函();
}
这有一个 moisture_sensor_tripped的优势()
及其亲属可以从其他的功能被称为没有你(或维护)记住的标记的顺序。
Let say I have an array of bool flags, it would be set to true or false depends on the condition.
Let say the index 1 ,2 ,6 have been set and all other flags are not set, I need to call functionA
, and if index 2,3, 5 have been set and all other flags are not set, I need to call functionB
. Is there an easy way where I could perform the logic above other than doing this:
if(array[1] == true && array[2] == true && array[6] == true &&
array[3] == false && array[4] == false && array[5] == false)
{
functionA();
}
Maintenance and readability nightmare!
Consider this instead:
bool temperature_sensor_tripped(const bool_array& flags)
{
return flags[1];
}
// [...]
if (temperature_sensor_tripped(array)
&& moisture_sensor_tripped(array)
&& !alarm_dispatched(array))
{
functionA();
}
This has the advantage that moisture_sensor_tripped()
and its kin can be called from other functions without you (or the maintainer) remembering the order of the flags.
这篇关于用旗阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!