我在enum
内有以下struct
:
struct FOODS
{
enum FRUIT
{
ORANGE,
BANANA,
PINEAPPLE
};
enum VEG
{
GINGER,
GARLIC,
ONION
};
enum DRINK
{
WATER,
COFFEE
};
};
我将它们用作std::vector
array[FOODS::FRUIT::ORANGE]
的数组索引ID,但我需要按顺序正确编制索引。我可以用:
struct FOODS
{
enum FRUIT
{
ORANGE = 0,
BANANA,
PINEAPPLE
};
enum VEG
{
GINGER = 3,
GARLIC,
ONION
};
enum DRINK
{
WATER = 6,
COFFEE
};
};
但是,如果顶部的两个中的任何一个发生变化,我必须手动管理所有三个枚举。有什么更好的方式呢?
答案 0 :(得分:1)
建议1:
struct FOODS
{
enum FRUIT
{
ORANGE,
BANANA,
PINEAPPLE,
FRUIT_SIZE
};
enum VEG
{
GINGER = FRUIT_SIZE,
GARLIC,
ONION,
VEG_SIZE
};
enum DRINK
{
WATER = VEG_SIZE,
COFFEE,
DRINK_SIZE
};
};
注意:您无法完成下一步:
struct FOODS {
enum FRUIT
{
ORANGE,
BANANA,
PINEAPPLE,
SIZE
};
enum VEG
{
GINGER = FRUIT_SIZE,
GARLIC,
ONION,
SIZE
};
enum DRINK
{
WATER = VEG_SIZE,
COFFEE,
SIZE
};
};
...因为你woluld有名称重新声明(FOODS::SIZE
)。
建议2:
struct FOODS
{
enum class FRUIT
{
ORANGE,
BANANA,
PINEAPPLE,
SIZE
};
enum class VEG
{
GINGER = FRUIT::SIZE,
GARLIC,
ONION,
SIZE
};
enum class DRINK
{
WATER = VEG::SIZE,
COFFEE,
SIZE
};
};
enum class
解决覆盖范围界定的名称
请注意,自C ++ 11以来,支持强枚举(enum class
)。