使用枚举表示从'int'到'type'的无效转换 [英] using enum says invalid conversion from 'int' to 'type'

查看:123
本文介绍了使用枚举表示从'int'到'type'的无效转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class myClass 
{
public:
枚举访问{
forL,
forM,
forA
};
typedef访问AccessType;
AccessType aType;
};

稍后定义一个这样的对象:

  myClass ob; 
ob-> aType = 0;

但是我收到这个错误:

 
错误:从'int'转换为'myClass :: AccessType {aka myClass :: access}'[-fpermissive]

不要枚举字段映射到整数?

解决方案

不,它们被存储为整数,但它们是不同的类型(例如,您甚至可以基于枚举类型重载)。您必须明确转换:

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

或者更好地写入枚举的相应命名值:

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

或者,如果要使用枚举作为一组整数常量,请更改类型字段:

  class myClass 
{
public:
枚举{
forL,
forM,
forA
};
int aType; //只是存储数字
};

从枚举到int的转换是隐式的。


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?

解决方案

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.

这篇关于使用枚举表示从'int'到'type'的无效转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆