枚举C ++获取索引 [英] Enum C++ Get by Index

查看:141
本文介绍了枚举C ++获取索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中想知道如果我有一个枚举可以访问第二个索引的值吗?例如我有

 枚举测试{hi,bye}; 

如果我想要我可以做一些类似Test [0]的事情,谢谢。 p>

解决方案

是和否。如果您的枚举没有明确的值,那么这是可能的。没有明确的值,枚举值以声明的顺序给出数值0-N。例如...

 枚举测试{
hi,// 0
bye // 1
}

这意味着索引只是转换为文字值。

  Test EnumOfIndex(int i){return static_cast< Test>(i); } 

这当然在运行时做了0次验证,一旦你添加了一个明确的值就会破坏下。但它将在默认情况下工作。


I was wondering in C++ if I have an enum can I access the value at the second index? For example I have

enum Test{hi, bye};

if I want 'hi', can I do something like Test[0], thanks.

解决方案

Yes and no. If your Enum does not have explicit values then it is possible. Without an explicit values, enum values are given numeric values 0-N in order of declaration. For example ...

enum Test {
  hi, // 0
  bye // 1
}

This means that indexes just translates into a literal value.

Test EnumOfIndex(int i) { return static_cast<Test>(i); }

This of course does 0 validation at runtime and as soon as you add an explicit value it will break down. But it will work in the default scenario.

这篇关于枚举C ++获取索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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