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

后端 未结 4 1649
隐瞒了意图╮
隐瞒了意图╮ 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: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.

提交回复
热议问题