Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

In my class I defined an enum like this:

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

Later in defined an object like this:

myClass ob; ob->aType = 0; 

However I get this error:

 error: invalid conversion from 'int' to 'myClass::AccessType {aka myClass::access}' [-fpermissive] 

Don't enum fields map to integers?

like image 778
mahmood Avatar asked Jan 02 '12 17:01

mahmood


1 Answers

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.

like image 95
Yakov Galka Avatar answered Sep 17 '22 15:09

Yakov Galka