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

标签 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;
 }

最佳答案

如果您不需要使用字符串来引用成员,那么执行此操作的方法称为“指向成员的指针”:

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
}

如果您确实需要使用字符串引用项目,内容中提到的另一种方式是使用 map 。如果您的所有成员都是同一类型,这会很有用。

#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;
}

关于c++ - 引用结构中成员的另一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23555620/

相关文章:

c++ - 如何使用级联阴影贴图制作柔和阴影?

c# - 如何将 DLL 访问代码从 C++ 移植到 C#

c++ - 2D C++ 碰撞检测几近完美,但还不够完美?

c++ - 将字节数组反序列化为结构

c++ - 操作系统和编译器如何通信以启动程序编译

c++ - 为什么定义没有返回类型的 main() 编译没有错误?

c++ - GTK Treeview 固定宽度

c++ - 在一个范围内生成无偏随机整数的最佳算法是什么?

c++ - 我可以像这样混合使用 pimpl 和 C 接口(interface)吗?

c++ - Codelite 问题——未指定可执行文件,请使用“target exec”