位标志作为例程中的输入进行验证
Bit flags as input in a routine for validating
#include <iostream>
using namespace std;
enum Property
{
HasClaws = 1 << 0,
CanFly = 1 << 1,
EatsFish = 1 << 2,
Endangered = 1 << 3
};
bool isHawk(int prop) // <-- Is the input type correct?
{
// If it can fly then also it is a hawk. If it has claws then also it is a hawk.
if (prop& HasClaws || prop& CanFly)
{
return true;
}
// If it can fly as well has claws then also it is a hawk.
if ((prop& (HasClaws | CanFly)) == (HasClaws | CanFly)) //<-- Can this be written cleaner/simpler
{
return true;
}
return false;
}
int main(int argc, char *argv[])
{
cout << "Value = " << isHawk(CanFly | HasClaws) << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
我的几个问题在上面的代码中是内联的。
在第二个if条件if ((prop& (HasClaws | CanFly)) == (HasClaws | CanFly))
,我真正想检查的是,它是否既能飞又有爪子。OR
是合适的运营商还是应该AND
?打电话给isHawk(CanFly | HasClaws)
时的问题也是如此。
一般来说,上面写的isHawk()
可以更简单/更干净的方式编写吗?
这只是一个示例代码。它与鹰或鹰无关。
输入类型是否正确?
将prop
定义为int
就可以了。 只要知道你有 28 个未使用的字节。 您可以考虑改用unsigned char
或unsigned short
来减少使用的位数。
这可以写得更干净/更简单吗
您可以向枚举添加另一个值,以将HasClaws
位和CanFly
位组合在一个名称下:
enum Property
{
HasClaws = 1 << 0,
CanFly = 1 << 1,
EatsFish = 1 << 2,
Endangered = 1 << 3,
HasClawsAndCanFly = HasClaws | CanFly
};
if ((prop & HasClawsAndCanFly) == HasClawsAndCanFly)
在第二个if条件
if ((prop& (HasClaws | CanFly)) == (HasClaws | CanFly))
,我真正想检查的是,它是否既能飞又有爪子。OR 是合适的运算符还是应该是 AND?
|
是正确的。 真正的问题是第一if
中的||
. 如果您单独传入HasClaws
或CanFly
,则在应该返回false
时返回true
:
isHawk(HasClaws) // returns true
isHawk(CanFly) // returns true
isHawk(HasClaws | CanFly) // returns true
isHawk(HasClawsAndCanFly) // returns true
您需要完全删除第一个if
:
bool isHawk(int prop)
{
if ( (prop & (HasClaws | CanFly)) == (HasClaws | CanFly))
//if ( (prop & HasClawsAndCanFly) == HasClawsAndCanFly)
{
return true;
}
return false;
}
然后可以简化:
bool isHawk(int prop)
{
return ((prop & (HasClaws | CanFly)) == (HasClaws | CanFly));
//return ((prop & HasClawsAndCanFly) == HasClawsAndCanFly);
}
相关文章:
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- cin 的十进制输入验证?
- 输入验证以筛选出字符、字符串和一系列整数
- 输入验证将数字放入向量中
- 在C++中使用字符数组进行输入验证
- 在C++中使用字符数组进行用户输入验证
- C++ 中字符数组的输入验证
- 检查节点的输入验证的整数
- 如何让我的程序在输入验证的基础上读取素数
- C++ 用户输入验证无法正常工作
- 程序终止,而不是继续整数输入验证循环
- 使用REGEX进行电子邮件输入验证C
- C++:输入验证器函数
- 将用户输入验证为整数:用户必须两次输入输入
- C 输入验证
- C :对输入验证函数进行编程的性能影响可以对其进行编程,而每次都可以将其编程
- 使用模板函数进行通用输入验证
- 为什么用于输入验证的 while 循环要么完全跳过循环,要么不考虑错误的输入
- 仅 C++ 字母和空格输入验证