引用结构中成员的另一种方法

时间:2014-05-09 02:16:54

标签: c++

现在,我正在学习如何在C++中正确使用结构。 是否有另一种方式来引用结构中的成员。

举个例子,下面是我的代码。 我想知道我是否可以像test.b那样在结构中引用name成员。

有没有令人难以置信的方法呢?

#include <iostream>

using namespace std;

struct A
 {
    string name = "Test";
 };

int main()
{
    A test;
    string b = "name";


    cout << test.name;
    return 0;
 }

2 个答案:

答案 0 :(得分:4)

如果您不需要使用字符串来引用该成员,那么执行此操作的方式称为&#34;指向成员的指针&#34;:

struct A
{
  int name;
  int value;
};

main()
{
  int A::* b = &A::name; // assign "name" to the variable called b

  struct A test = {1,2}; // make a structure and fill it in

  return test.*b;        // use the variable called b to reference test.name
}

如果您确实需要使用字符串重新添加项目,则内容中提到的其他方法是使用地图。如果您的所有成员都是同一类型,那么这将非常有用。

#include <iostream>
#include <map>

main()
{
  std::map<std::string,int> test; // make something that can be keyed by a string

  test["name"]=1; // put something called "name" in the map with a value of 1
  test["value"]=2; // put something called "value" in the map with a value of 2

  std::cout << test["name"] << std::endl;

  return 0;
}

答案 1 :(得分:3)

您所指的是Reflection(按名称访问功能/属性)。默认情况下,C ++没有反射。所以你可能需要为此寻找库/框架。谷歌“C ++反思”。 Boost是C ++反射/序列化的解决方案之一。

相关问题