gpt4 book ai didi

c++ - 使用枚举表示从 'int' 到 'type' 的转换无效

转载 作者:IT老高 更新时间:2023-10-28 21:34:25 25 4
gpt4 key购买 nike

在我的类里面,我定义了一个这样的枚举:

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

后来定义了一个这样的对象:

myClass ob;
ob->aType = 0;

但是我得到了这个错误:

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

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

最佳答案

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

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

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

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

或者,如果您想将枚举仅用作一组整数常量,请更改字段的类型:

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

从 enum 到 int 的转换是隐式的。

关于c++ - 使用枚举表示从 'int' 到 'type' 的转换无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8703743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com