简体   繁体   English

使用C / C ++中的枚举

[英]Working with enums in C/C++

I am working on an adaption of the code shown here , however, instead of using individual values I want to create an enum of possible values. 我正在努力调整此处显示的代码,但是,我想创建一个可能值的枚举,而不是使用单个值。

I would like to keep this in the header file if possible, and I would like it to include the values something like... 如果可能的话,我想将它保留在头文件中,我希望它包含类似于......的值。

enum Notes{
    NOTE_B0 = 31,
    NOTE_C1 = 33,
    NOTE_CS1 = 35
};

Now I am looking to iterate through the enum values, how would I do this? 现在我希望迭代枚举值,我该怎么做?

Also can I store values over 255? 我还可以存储超过255的值吗?

The best you can do is create a static const array of all the enum values somewhere and iterate through that. 你能做的最好的事情是在某处创建一个包含所有枚举值的静态const数组,然后迭代它。 If the enum values were all consecutive you could obviously iterate through them easily enough, but short of that you're out of luck. 如果枚举值都是连续的,你很明显可以很容易地遍历它们,但如果你运气不好。

You can store all values which fit in the underlying integer type. 您可以存储适合基础整数类型的所有值。 With C++11 you can specify the underlying integer. 使用C ++ 11,您可以指定基础整数。 If you don't specify it the compiler will try to find one into which all values fit. 如果您没有指定它,编译器将尝试找到所有值都适合的那个。

Iteration is not possible, because enum elements are only compile time values. 迭代是不可能的,因为枚举元素只是编译时间值。 There is no need for the compiler to store them at runtime. 编译器不需要在运行时存储它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM