我可以在c ++中定义枚举的大小吗? [英] Can I define the size of an enum in c++?

查看:124
本文介绍了我可以在c ++中定义枚举的大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我所知道的(从我在cpp编程语言中读取的),大小将是一些整数类型的大小,可以保持其范围,不大于sizeof(int),除非枚举不能表示为一个int或一个unsigned int。



但是是否可以用某种方式定义大小?例如,我想使用一个枚举,其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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆