现在,我正在学习如何在 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/