将数字附加到枚举以获得其他枚举

问题描述 投票:1回答:1

我想通过附加一个数字在for循环中获得枚举值,例如

enum example
{
Example_1,
Example_2,
Example_3,
.
.
.
Example_n
};
example x;
for (i = 0; i < n; i++
{x = Example_ + i; // if i = 5, I need Example_5
}

我想要在C ++ 11中实现此功能

c c++11 for-loop enums enumeration
1个回答
1
投票

如果枚举中包含Example_0,则Example_0 + 5将为您提供一个等于Example_5的整数值。枚举只是整数。

所有这些都假设您没有为某个枚举常量明确分配值-这是另一回事。


0
投票

您可以使用带有宏的令牌粘贴运算符(##)来完成此操作

#define getexample(x) Example_##x

那么你会

for (i = 0; i < n; i++
{
    x = getexample(i);
}

更多信息,请参考these docsthese docs

© www.soinside.com 2019 - 2024. All rights reserved.