使用integer显示枚举类型的值
display values of enum type from using integer
我想通过使用enumType变量来获取当前状态。但有了这些代码,我无法获得值。。例如,如果enumType=3,则状态应为爬网。。。
#include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;
int main()
{
int enumType;
srand((unsigned)time(0));
enumType = rand()%3;
enum state{
stand,
walk,
run,
crawl,
};
state currentState;
(int)currentState =enumType;
cout<<state.currentState;
system("pause");
return 0;
}
老兄。C/C++不是这样工作的:)。如果您想要"有意义的名称"(如"enum state 3"=="crawl"),那么您可以自己将枚举值映射到文本字符串。
你可以创建一个静态表,你可以使用"switch/case"块,你可以用STL映射。有很多选择,但你必须自己手动完成。它并不是自动内置到语言中的(比如C#)。
string strState;
switch(currentState)
{
case stand:
strState = "Stand";
break;
case walk:
strState = "walk";
break;
case run:
strState = "run";
break;
case crawl:
strState = "crawl";
break;
}
cout << strState;
这就是您所需要的:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include <cstdlib>
#include <ctime>
int main()
{
srand(time(0));
enum state{
stand,
walk,
run,
crawl,
};
state min=stand;
state max=crawl;
state enumType = (state)(rand()%((max-min)+1));
state currentState;
currentState =enumType;
printf(" %i ",currentState);
return 0;
}
结果是:
11.01.02.。。。每次运行,0-2之间的值不同,因为它是"地板"新编辑:(max-min)+1)在模块化的东西
相关文章:
- 在有符号基础类型枚举的位域上溢出
- 在编译时将强类型枚举器转换为其基础类型?
- 如果 int 是"not within the enums range",为什么将 int 转换为强类型枚举会编译?
- 类型枚举的变量不是类型名称
- 强类型枚举的语法实现错误
- 枚举与强类型枚举
- 错误:T没有命名类型-用于使用强类型枚举的专门化
- 如何使用强类型枚举
- QT:将强类型枚举参数传递到插槽
- 在类定义中声明类型(枚举、结构等)会增加代码大小
- Visual Studio 11 (beta) 中的强类型枚举类
- 使用强类型枚举对类型和子类型进行建模
- 不允许将强类型枚举用作同一基础类型的参数
- 如何正确使用C++强类型枚举
- 带有强类型枚举的模板参数推导
- 是否可以在googleprotobuf中为类型(枚举或消息)定义一个别名
- C++中默认初始化的全局强类型枚举是什么
- std::is_signed不适用于强类型枚举:int
- 如何定义自定义值的类型?(枚举类型定义)
- 将强类型枚举传递给函数