ENUM中值的数组

Array of values within an ENUM?

本文关键字:数组 ENUM      更新时间:2023-10-16

我有这样的代码

enum type {NOTHING, SOMETHING, SOMETHINGELSE}
type *x;

目前我使用x[765] == SOMETHING为例,我如何存储其他值,例如

x[765] == SOMETHINGELSE;
x[765].position == 43.5;
x[765].somevar == 12;

我为我的问题措辞不恰当而道歉,我刚开始学习c++,我知道我想要什么,我只是不确定如何问。

谢谢。

看起来你在寻找一种构建"知识"的方法;这可以通过结构体或类来完成:

#include <vector>
struct Info {
   enum thingness { nothing, something };
   // 'member' variables
   thingness howMuch;
   int a_counter;
   float position;
};
int main(){
  Info object;
  object.howMuch=Info::something;
  object.a_counter=1;
  object.position=5.4;

您可以将这些类型的对象分组到一个容器中-通常是std::vector:

  // a container of InterestingValues
  std::vector<Info> container(300);
  container[299].howMuch=Info::nothing;
  container[299].a_counter=4;
  container[299].position = 3.3;
  // or assign rightaway:
  container[2] = object;
}

你将不得不为自己设置一个更复杂的类型:

struct type
{
    enum flag_type
    {
        NOTHING, SOMETHING, SOMETHINGELSE
    } flag;
    double position;
    int somevar;
};

,然后有一个新的type.数组

找一本好书来学习。这里有一本好书的列表:权威c++书籍指南和列表

在c++中,你问的是如何声明结构数组。试试这个:

struct type {
    double position;
    int somevar;
};
type *x;
x[765].position = 43.5;
x[765].somevar = 12;

enum基本上是int类型的可替换标签。你需要定义一个结构或类。

struct type
{
   float position ;
};
type var;
var.position = 3.4;

类型enum需要是类的成员,以及其他字段。例如,

class MyType
{
public:
    type t;
    double position;
    int somevar;
};

使用MyType实例数组

MyType *x;

你就可以做你想做的事了

x[765].t = SOMETHINGELSE;