我可以在c ++中定义枚举的大小吗? [英] Can I define the size of an enum in c++?
问题描述
但是是否可以用某种方式定义大小?例如,我想使用一个枚举,其sizeof是自然字(通常是unsigned long)的大小。
你可以在C ++ 11中:
enum / * class * / MyEnum:unsigned long
{
Val1,
Val2
};
(您可以为旧样式指定枚举大小枚举
或新式枚举类
。)
利用您引用的句子的最后一个短语优化了枚举的最小大小:
枚举MyEnum
{
Val1,
Val2,
ForceSize = 0xFFFFFFFF //不使用
};
...这将确保枚举为至少32位。
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), unless an enumerator cannot be represented as an int or as an unsigned int".
But is it possible to define the size in some way? For example, I would like to use an enum whose sizeof is the size of the natural word (usually unsigned long).
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.
这篇关于我可以在c ++中定义枚举的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!