枚举具有整数范围

时间:2014-03-29 21:40:01

标签: c++ enums

我希望doorPosition_DEG的值介于1-90(度)之间。是否有可能做到这一点?方便吗?

enum doorPosition_DEG {0,1,2,3,4... 90 };

似乎enum doorPosition_DEG { 0-90 };无效

1 个答案:

答案 0 :(得分:0)

不,不可能这样做。你必须给每个人一个自己的名字。你有几个选择:

你可以给每个人一个自己的名字。

您可以使用int,并在必要时验证它是否为[0,90]:

int doorPosition = 32; // e.g. when storing

// or when using (use whatever error handling you'd like)
void setDoorPosition (int pos) {
   if (pos < 0 || pos > 90)
      throw runtime_error("Door position must be from 0 to 90.");
}

如果您想清楚它,可以使用typedef(当然,您仍需要明确检查范围):

typedef int DoorPosition;

您还可以定义一个用于表示位置的小型自定义类,0 <= position <= 90作为不变量,例如:

class DoorPosition {

private:

  int position;

public: 

  explicit DoorPosition (int p) {
     setPosition(p);
  }

  void setPosition (int p) {
     if (p < 0 || p > 90)
        throw runtime_error("Door position must be from 0 to 90.");
     // ^ or optionally clamp to valid range, if that's more appropriate
     position = p;
  }

  int getPosition () const {
     return position;
  }

};

根据需要覆盖各种有用的运算符。

相关问题