具有重复的枚举值
我正在用 C++ 创建一个俄罗斯方块克隆,并且有一个枚举 GameProperty
,其指定如下:
enum GameProperty {
NUM_OF_TETROMINOES = 7,
NUM_OF_TILES = 4,
TETROMINO_ROTATIONS = 4
};
在我的例子中,我仅在循环访问时使用这些值。 tetromino 的图块,例如:
for (int i = 0; i < TETROMINO_TILES; i++) { }
在任何情况下,拥有多个具有相同值的枚举器是否被认为是不好的做法?
I'm creating a Tetris clone in C++, and I have an enum GameProperty
, which is specified as follows:
enum GameProperty {
NUM_OF_TETROMINOES = 7,
NUM_OF_TILES = 4,
TETROMINO_ROTATIONS = 4
};
In my case, I only use these values when looping through a tetromino's tiles, e.g:
for (int i = 0; i < TETROMINO_TILES; i++) { }
Is it under any circumstance considered bad practice to have multiple enumerators with the same value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这些不应该是单个
枚举
中的值。它们应该是单独的常量。要了解原因,请查看类似i <; 的代码。 TETROMINO_TILES
。它将integer
与GameProperty
进行比较,后者可以具有诸如TETROMINO_ROTATIONS
之类的值。这毫无意义。These should not be values in a single
enum
. They should be separate constants. To see why, look at code likei < TETROMINO_TILES
. The compares aninteger
to aGameProperty
which can have values likeTETROMINO_ROTATIONS
. That makes no sense.当您想要创建一个新的、不同的类型,而该类型实际上不是一个标量值时,请使用
enum
。例如,颜色可以被枚举,因此可以编号,但这些数字实际上没有任何意义。如果您为枚举器分配有意义的数字,则表明您可能确实想要这样的东西:
现在您可以使用相同的语法以及
using
声明,并且这些常量可以在 < code>for 循环和表达式,无需转换。再举一个例子,以下内容都是正确的,但不应在
enum
和int
之间交换:Use
enum
when you want to create a new, distinct type which isn't really a scalar value. For example, colors can be enumerated, and hence numbered, but those numbers don't really mean anything.If you're assigning meaningful numbers to the enumerators, it's a sign that you might really want something like this:
Now you can use the same syntax, as well as
using
declarations, and these constants work infor
loops and expressions with no conversion.For another example, the following are both correct but shouldn't be swapped between
enum
andint
:就像定义类一样定义枚举。从概念上讲,它应该是一个属性的值的集合,而不是装配多个属性。
Define a enum just like you define a class. It should conceptually be a collection of values for ONE property, instead of multiple properties rigged up.