从字符串转换时如何组合多个枚举?

时间:2017-01-17 22:01:41

标签: c++ class enums

this question on Code Review的启发,我正在学习一些C ++的基础知识,部分是通过编写Pokedex。我目前正处于我在枚举中定义口袋妖怪类型的地步:

enum class basicPokemonType
{
    Normal,
    Fire,
    Water,    
    //etc.
};

在Code Review上接受的答案中,作者然后建议将这些组合成一个组合课程,我的工作如下(评论是为了确保我明白我在做什么):

class combinedPokemonType
{
    combinedPokemonType(basicPokemonType primary);
    combinedPokemonType(basicPokemonType primary, basicPokemonType secondary); //overloading constructor in case we have two types

    combinedPokemonType convertStringToPokemonType(std::string primary, std::string secondary = "")

};

在代码中,我将每个Pokemon从一个文本文件读入一个流,如下例所示:

  

1,Bulbasaur,草和毒药,15.2,28,男性和女性,0,

正如您所看到的,口袋妖怪可以有多种类型。我将当前函数转换为我定义的枚举的函数如下:

combinedPokemonType combinedPokemonType::convertStringToPokemonType(std::string primary, std::string secondary="")
{
    if (primary == "Normal")
    {
        return combinedPokemonType(basicPokemonType::Normal);
    }
    else if (primary == "Fire")
    {
        return combinedPokemonType(basicPokemonType::Fire);
    }
    else if (primary == "Water")
    {
        return combinedPokemonType(basicPokemonType::Water);
    }
    // etc.
}

如何涵盖两种以上的情况?我是否需要继续我的if声明并定义每个声明之间的所有可能组合?我不禁觉得必须有一个更简单的方法。

或者,如果我遗漏了一些明显的东西,或者尝试的东西显然远远超出我目前的能力,请随时告诉我。

2 个答案:

答案 0 :(得分:3)

我通常的建议是将其作为std::mapstd::unordered_map

实施
std::map<std::string, basicPokemonType> const types_map = {
{"Fire", basicPokemonType::Fire},
{"Normal", basicPokemonType::Normal},
{"Water", basicPokemonType::Water},
/*...*/
};

combinedPokemonType combinedPokemonType::convertStringToPokemonType(std::string primary, std::string secondary="")
{
    auto it = types_map.find(primary);
    if(it != types_map.end())
        return combinedPokemonType(*it);
    else
        //Whatever your error condition is if the string isn't a valid type
}

这并不能阻止您写出每一对,但它确实使代码更清晰,并减少重复的if / else if / else语句。

答案 1 :(得分:0)

您可以将口袋妖怪的类型实现为具有set原始类型。要检查口袋妖怪是否是特定类型,您可以询问口袋妖怪的类型集以查看它是否包含该原始类型。这也是灵活的,因为如果它们被添加,它将支持三种或更多种类的口袋妖怪。