C++:如何访问名称存储在数组中的成员变量

假设我有一个这样的字符串数组:

string registers[2] = {"r0","r1"}

和这样的结构:

struct cpu {
    int r1;
}

我试过这样的事情:

cpu *p = (cpu*)malloc(sizeof(cpu));
cout << p->registers[1] << endl;

但这给出了编译错误。如何实施?

编辑:问题描述

我需要使用索引访问 cpu 类的成员,所以我想我可以将成员的名称放在数组中,然后使用索引获取成员的名称

回答

您的代码格式完全错误。表达式p->registers使用默认运算符-> ,该运算符要求左手运算符是指向类型的指针,该类型将具有名称用作右手运算符 ( registers) 的成员。你的cpu不包含registers.

无论出于何种原因,模仿您想要的行为的步骤:

  1. 设计一种方法,通过索引或指向成员的指针将特定对象string与 的成员相关联cpu
  2. 将字符串值映射到索引或指向成员的指针。
  3. C++ 允许使用成员运算符来封装它,这将导致类似p["r0"]产生对r0.

在最简单的情况下,当所有元素的类型相同时,您可以只使用 astd::map或类似设计的类,例如

struct cpu {
    std::map<std::string, int> registers;

    // constructor initializes the map
    cpu() : registers ( { {"r0", 0}, 
                          {"r1", 0} 
                        }) 
    {}
};

这里的表达式p->registers["r0"]会给你参考与“r0”键等关联的值。

注意cpu 对象的创建应该是

cpu *p = new cpu();

  • @LipunPanda here you are, but honestly, be considerate with what you do, I have no comprehension of real task to offer proper solution and you apparently struggle with basics. THis example got own costs

以上是C++:如何访问名称存储在数组中的成员变量的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>