【C++】【Qt】位兼容的枚举写法,可以按位或

用于作为有多种属性的方法的输入参数

具体见Qt代码

#include 
#include 

class TestEnumClass
{
public:
    enum TestEnum
    {
        TEST_ALL_NO = 0x0,
        TEST_A = 0x0001,
        TEST_B = 0x0002,
        TEST_C = 0x0004
    };

    TestEnumClass() {}

    static void test(int testEnum)
    {
        if(testEnum == TEST_ALL_NO)
        {
            qDebug()<<"nothing to do\n over\n";
            return;
        }

        if(testEnum & TEST_A)
        {
            qDebug()<<"Test A";
        }

        if(testEnum & TEST_B)
        {
            qDebug()<<"Test B";
        }

        if(testEnum & TEST_C)
        {
            qDebug()<<"Test C";
        }

        qDebug()<<"over\n";
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    TestEnumClass::test(TestEnumClass::TEST_ALL_NO);
    TestEnumClass::test(TestEnumClass::TEST_A);
    TestEnumClass::test(TestEnumClass::TEST_B);
    TestEnumClass::test(TestEnumClass::TEST_C);
    TestEnumClass::test(TestEnumClass::TEST_A | TestEnumClass::TEST_B);
    TestEnumClass::test(TestEnumClass::TEST_A | TestEnumClass::TEST_C);
    TestEnumClass::test(TestEnumClass::TEST_B | TestEnumClass::TEST_C);
    TestEnumClass::test(TestEnumClass::TEST_A | TestEnumClass::TEST_C | TestEnumClass::TEST_B);

    return a.exec();
}

更新一个基于Qt moc的实现,具体可见Qt的QFlags的文档,代码如下:

#include 
#include 

class TestEnumClass
{
public:
    enum TestEnum
    {
        TEST_ALL_NO = 0x0,
        TEST_A = 0x0001,
        TEST_B = 0x0002,
        TEST_C = 0x0004
    };
    Q_DECLARE_FLAGS(TestEnums, TestEnum)

    TestEnumClass() {}

    static void test(TestEnumClass::TestEnums t)
    {
        //int t = static_cast(testEnum);
        if(t == TEST_ALL_NO)
        {
            qDebug()<<"nothing to do\n over\n";
            return;
        }

        if(t & TestEnum::TEST_A)
        {
            qDebug()<<"Test A";
        }

        if(t & TestEnum::TEST_B)
        {
            qDebug()<<"Test B";
        }

        if(t & TestEnum::TEST_C)
        {
            qDebug()<<"Test C";
        }

        qDebug()<<"over\n";
    }
};
Q_DECLARE_OPERATORS_FOR_FLAGS(TestEnumClass::TestEnums)

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    TestEnumClass::test(TestEnumClass::TEST_ALL_NO);
    TestEnumClass::test(TestEnumClass::TEST_A);
    TestEnumClass::test(TestEnumClass::TEST_B);
    TestEnumClass::test(TestEnumClass::TEST_C);
    TestEnumClass::test(TestEnumClass::TEST_A | TestEnumClass::TEST_B);
    TestEnumClass::test(TestEnumClass::TEST_A | TestEnumClass::TEST_C);
    TestEnumClass::test(TestEnumClass::TEST_B | TestEnumClass::TEST_C);
    TestEnumClass::test(TestEnumClass::TEST_A | TestEnumClass::TEST_C | TestEnumClass::TEST_B);

    return a.exec();
}


你可能感兴趣的:(C++,QT)