Some knowledge points about enumeration

"C++ Programming Language (Fourth Edition)" Chapter 8.4

1. Enumeration is divided into two types of enum class and enum. The former enumeration value will not be implicitly converted to other types, and the latter value will be converted to an integer. The former should generally be used.

2. The enumeration value type is generally int. If you think the int type is a waste of space, you can also explicitly specify other types:

enum class color:char
{
    red,
    green,
    yellow
};

3. Bit operation of enumeration:

enum class color:char
{
    red = 5,
    green = 6,
    yellow = 7
};

constexpr color operator |(color c1,color c2)
{
    return static_cast<color>(static_cast<int>(c1) | static_cast<int>(c2));
}

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    color c1 = color::red;
    color c2 = color::green;
    color c3 = c1 | c2;
    debug static_cast<int>(c3) << (c3 == color::yellow);// 5 | 6 = 7
}

4. The value of sizeof() of the enumeration is equal to the value of (int \ char) sizeof() of the enumeration value type.

5. If enumeration does not have to be used to declare objects, anonymous enumeration can be used:

enum color:int
{
    red = 666,
    green = 999,
    yellow = 444
};

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    int c = red;
    debug c;
}

Guess you like

Origin blog.csdn.net/kenfan1647/article/details/113815750