将值分配给枚举类型

the*_*ux4 6 c++ string enums enumeration

enum options {Yes,No};

class A{
    int i;
    string str;
    options opt;
};


int main{
    A obj;
    obj.i=5;
    obj.str="fine";
    obj.opt="Yes"; // compiler error
}
Run Code Online (Sandbox Code Playgroud)

如何指定const char *选择?

Dou*_* T. 14

做就是了

   obj.opt=Yes;
Run Code Online (Sandbox Code Playgroud)

这段代码:

   obj.opt="Yes";
Run Code Online (Sandbox Code Playgroud)

尝试将字符串文字(完全不同的类型)分配给枚举类型,C++不会为您自动转换.

如何指定const char*来选择?

你必须手动执行此操作,我喜欢保留一组免费函数,以便使用我的枚举进行这样的转换,即我将我的枚举包装在命名空间中并提供一些函数来处理它们:

namespace options
{
   enum Enum {Yes,No,Invalid};
   Enum FromString(const std::string& str);
   // might also add ToString, ToInt, FromInt to help with conversions
}

Enum  FromString(const std::string& str)
{
    if (str == "Yes")
    { 
        return Yes        
    }
    else if (str == "No")
    {
        return No;
    }
    return Invalid; //optionally throw exception
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

 class A{
   int i;
   string str;
   options::Enum opt; // notice change here
 };

 ...


obj.opt=options::FromString("Yes");
Run Code Online (Sandbox Code Playgroud)

所以你可以看到,C++中的枚举可能不会给你其他语言中所有的枚举和口哨.你必须自己手动转换东西.