Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 555
thetux4 Avatar asked May 09 '11 14:05

thetux4


4 Answers

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.

like image 97
Doug T. Avatar answered Sep 18 '22 17:09

Doug T.


Enums are not strings, but just values

obj.opt = Yes;
like image 26
Bo Persson Avatar answered Sep 19 '22 17:09

Bo Persson


Because an enum value is not a string. This is correct :

int main{
    A obj;

    obj.opt=Yes;
}
like image 45
BЈовић Avatar answered Sep 20 '22 17:09

BЈовић


You can't do this. You will have to use some string comparisons and set it.

like image 29
Daniel A. White Avatar answered Sep 19 '22 17:09

Daniel A. White