Search code examples
c++stringenumsenumeration

Assigning values to enumerated types


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
}

How can assign const char * to opt?


Solution

  • Just do

       obj.opt=Yes;
    

    This code:

       obj.opt="Yes";
    

    attempts to assign a string literal (a completely different type) to an enum type, which C++ doesn't automagically convert for you.

    How can assign const char * to opt?

    You'll have to do this manually, I like to keep a set of free functions around for doing conversions like this with my enums, ie I'll wrap my enums in a namespace and provide some functions for working with them:

    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
    }
    

    Now you can do:

     class A{
       int i;
       string str;
       options::Enum opt; // notice change here
     };
    
     ...
    
    
    obj.opt=options::FromString("Yes");
    

    So you can see, enums in C++ probably don't give you all the bells and whistles of enums in other languages. You'll have to manually convert things yourself.