C++:如何访问名称存储在数组中的成员变量 [英] C++: How to access a member variable whose name is stored in an array

查看:35
本文介绍了C++:如何访问名称存储在数组中的成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a string array like this:

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

还有这样的结构:

struct cpu {
    int r1;
}

我尝试过这样的事情:

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

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

But this gave a compilation error. How to implement this?

问题描述

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

I need to access the member of a cpu class using an index so I thought I could just put the names of the memebers in an array and then get the name of the member using the index

推荐答案

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

Your code is completely illformed. Expression p->registers uses default operator -> which requires left-hand operator to be a pointer to a type which would have a member with name used as right-hand operator (registers). Your cpu doesn't contain registers.

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

Steps to emulate behaviour like one you desire for whatever reason that is:

  1. 设计一种方法,通过索引或指向成员的指针将特定的stringcpu 的成员相关联.
  2. 将字符串值映射到索引或指向成员的指针.
  3. C++ 允许使用成员运算符来封装它,这将导致类似 p[r0"] 的内容产生对 r0 的引用.
  1. design a way to associate particular string to a member of cpu, by index or pointer to member.
  2. map the string value to an index or a pointer to member.
  3. C++ allows to encapsulate that using member operators,which would result in something like p["r0"] yielding a reference to r0.

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

In simplest case, when all elements are of same type, you may just use a std::map or a class designed similarly, e.g.

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

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

这里的表达式 p->registers[r0"] 将提供对与r0"关联的值的引用.钥匙等

Here an expression p->registers["r0"] would give you reference to value associated with "r0" key, etc.

注意 cpu对象的创建应该是

NB The creation of cpu object should be

cpu *p = new cpu();

这篇关于C++:如何访问名称存储在数组中的成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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