Can I define the size of an enum in c++?

后端 未结 2 1526
悲&欢浪女
悲&欢浪女 2021-01-03 22:27

From what I know (from what I read in the cpp-programming-language) the size would be the size of \"some integral type that can hold its range and not larger than sizeof(int

2条回答
  •  忘掉有多难
    2021-01-03 23:02

    You can in C++11:

    enum /*class*/ MyEnum : unsigned long
    {
        Val1,
        Val2
    };
    

    (You can specify the size of an enum either for the old-style enum or the new-style enum class.)

    You can also increase the minimum size of an enum by fun trickery, taking advantage of the last phrase of the sentence that you cited:

    enum MyEnum
    {
        Val1,
        Val2,
        ForceSize = 0xFFFFFFFF // do not use
    };
    

    …which will ensure that the enum is at least 32-bit.

提交回复
热议问题