gpt4 book ai didi

c++ - 位标志作为验证例程中的输入

转载 作者:行者123 更新时间:2023-11-28 06:20:23 25 4
gpt4 key购买 nike

#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()可以写得更简单/更干净吗?

这只是一个示例代码。这与鹰派或成为鹰派无关。

最佳答案

Is the input type correct?

prop 定义为 int 就可以了。只知道您有 28 个未使用的字节。您可以考虑使用 unsigned charunsigned short 来减少使用的位数。

Can this be written cleaner/simpler

您可以向您的枚举添加另一个值,以将 HasClawsCanFly 位组合在一个名称下:

enum Property
{
HasClaws = 1 << 0,
CanFly = 1 << 1,
EatsFish = 1 << 2,
Endangered = 1 << 3,
HasClawsAndCanFly = HasClaws | CanFly
};

if ((prop & HasClawsAndCanFly) == HasClawsAndCanFly)

In the second if condition if ((prop& (HasClaws | CanFly)) == (HasClaws | CanFly)), what I really wanted to check is, if it can both fly as well as has claws. Is OR the right operator for this or should it be AND?

| 是正确的。真正的问题是第一个 if 中的 ||。如果您单独传入 HasClawsCanFly,您将返回 true 而您应该返回 false :

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++ - 位标志作为验证例程中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29404149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com