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

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()可以写成simpler/cleaner的方式吗?

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

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,则在您应该返回 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);
}