Assigning values to enumerated types

17,578

Solution 1

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.

Solution 2

Enums are not strings, but just values

obj.opt = Yes;

Solution 3

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

int main{
    A obj;

    obj.opt=Yes;
}

Solution 4

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

Solution 5

In your case you can "convert" enum to const char*. All what you need is to create macro. For example: #define ENUM_TO_CSTR(x) #x and then: obj.opt=ENUM_TO_CSTR(Yes).

This macro will convert everything you pass to it into C-like string. It won't convert variable value, but only its name!

int x = 10; cout << ENUM_TO_CSTR(x) << endl;

Will print x (not 10) on screen, so be careful using it!

Share:
17,578
thetux4
Author by

thetux4

Updated on August 04, 2022

Comments

  • thetux4
    thetux4 over 1 year
    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?

  • Matthieu M.
    Matthieu M. almost 13 years
    I provide the from/to string conversion functions as well (in fact I've wrapped the enum creation in a macro just so that they are provided all times), it just is easier to read in debug logs and to pass as parameters (to be parsed).