使用枚举作为数组索引 [英] Using an enum as an array index

查看:564
本文介绍了使用枚举作为数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个枚举:

 枚举ButtonState {
BUTTON_NORMAL = 0,
BUTTON_PRESSED = 1 ,
BUTTON_CLICKED = 2
};

const u8 NUM_BUTTON_STATES = 3;

在我的Button类中,我有成员变量 ButtonState state; ButtonColors颜色[NUM_BUTTON_STATES]; 。当绘制按钮时,我使用 colors [state] 来获取按钮所处的状态的颜色。



我的问题:


  1. 这是好的编程风格吗?有更好的方法吗? (我通常只使用带有switch语句的枚举...使用枚举作为数组索引感觉不太正确。)

  2. 我枚举的值?它似乎从0开始默认情况下增加1,但是它保证在所有编译器中这样工作。


解决方案

这是好的编程风格吗?





  class Button 
{
public:
//用于数组索引!不要更改数字!
枚举状态{
NORMAL = 0,
PRESSED,
CLICKED,
NUMBER_OF_BUTTON_STATES
};
};

缺点是 NUMBER_OF_BUTTON_STATES 现在是有效的状态值。不是一个大问题,如果你传递这些值周围作为 ints



使用枚举作为数组索引doesn'



没关系。只需 DOCUMENT 即可,所以下一个人知道发生了什么!



我必须指定枚举的值吗 p>

没有'='赋值,枚举的应该从零开始向上增加。



如果枚举项具有=分配的值,则后续的非'='枚举项继续从中计数。



源:参考手册,第113页



也就是说,我喜欢指定初始值,以使代码更清晰。


I have this enum:

enum ButtonState {
    BUTTON_NORMAL = 0,
    BUTTON_PRESSED = 1,
    BUTTON_CLICKED = 2
};

const u8 NUM_BUTTON_STATES = 3;

In my Button class I have member variables ButtonState state; and ButtonColors colors[NUM_BUTTON_STATES];. When drawing the button, I use colors[state] to get the colours for whatever state the button is in.

My questions:

  1. Is this good programming style? Is there a better way to do it? (I usually only use enums with switch statements... using an enum as an array index doesn't feel right.)
  2. Do I have to specify the values of the enum? It seems to start from 0 by default and increment by 1 but is it guaranteed to work that way in all compilers?

解决方案

Is this good programming style?

I think so. I do the same thing quite frequently.

Is there a better way to do it?

class Button
{
public:
    // Used for array indexes!  Don't change the numbers!
  enum State {
    NORMAL = 0,
    PRESSED,
    CLICKED,
    NUMBER_OF_BUTTON_STATES
  };
};

Drawback is that NUMBER_OF_BUTTON_STATES is now a valid Button::State value. Not a big issue if you are passing these values around as ints. But trouble if you are actually expecting a Button::State.

Using an enum as an array index doesn't feel right.

It's fine. Just DOCUMENT it, so the next guy knows what's going on! (That's what comments are for.)

Do I have to specify the values of the enum?

With no '=' assignment, enum's are supposed to start at zero and increment upwards.

If a enum entry has an '=' assigned value, subsequent non '=' enum entries continue counting from there.

Source: The Annotated C++ Reference Manual, pg 113

That said, I like to specify the initial value just to make the code that much clearer.

这篇关于使用枚举作为数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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