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

Bit flags as input in a routine for validating

本文关键字:输入 验证 标志 例程      更新时间:2023-10-16
#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 charunsigned 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中的||. 如果您单独传入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);
}