using enum says invalid conversion from 'int' to 'type'

后端 未结 4 1661
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 02:51

In my class I defined an enum like this:

class myClass 
{
 public:
    enum access {
      forL,
      forM,
      forA
    };
    typedef access AccessType;
            


        
相关标签:
4条回答
  • 2021-02-05 03:16

    No, they are stored as integers but they are distinct types (e.g. you can even overload based on the enum type). You must convert explicitly:

    myClass ob;
    ob->aType = (myClass::AccessType)0;
    

    or ever better write the corresponding named value of the enum:

    myClass ob;
    ob->aType = myClass::forL;
    

    Or perhaps if you want to use the enum just as a set of integer constants, change the type of the field:

    class myClass 
    {
     public:
        enum {
          forL,
          forM,
          forA
        };
        int aType; // just stores numbers
    };
    

    Conversion from enum to int is implicit.

    0 讨论(0)
  • 2021-02-05 03:22

    I just had same issue. i have to initialize an object from what i read in an xml file and for sure, i have no control over what could happen to that file.

    Constructor has an enum as argument :

    enum status_t { NOT_STARTED, STARTED, DONE };
    MyObject::MyObject(int id, status_t status) : m_id(id), m_status(status){}
    

    So when parsing the Xml i have to cast it. I prefered then to handle the cast in the constructor so the other classes do not have to know which is the valid enums.

    MyObject::MyObject(int id, int status) : m_id(id){
        m_status = status_t(status);
    }
    

    But no way to be sure the value coming from xml will be in the correct range.

    Here is the solution i came with :

    MyObject::MyObject(int id, int status) : m_id(id){
        switch(status){
            case NOT_STARTED:
            case STARTED:
            case DONE:
                m_status=status_t(status);
                break;
            default:
                m_status=NOT_STARTED;
                break;
        }
    }
    

    This is an implementation choice, to force a default value in case of non consistent data. One could prefer throwing out an exception, in my case it will do this way.

    0 讨论(0)
  • 2021-02-05 03:27

    Enumeration members are backed by integer values but there is no implicit conversion from an integer to an enum type. You need to use an explicit cast if you really want to write it like this:

    ob->aType = static_cast<myClass::access>(0);
    
    0 讨论(0)
  • 2021-02-05 03:37

    You can't do an implicit cast from int -> enum, since at compile time there is no way to know that the cast is valid.

    You can do implicit casts the other way, so you could (if you wanted to) do:

    int foo = forL;
    
    0 讨论(0)
提交回复
热议问题