在运行时按其名称访问类成员变量 [英] Accessing a class member variable by its name at runtime
本文介绍了在运行时按其名称访问类成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在更多不可能但确实是问题的脉络中:
In the vein of more impossible-but-is-it-really questions:
是否可以访问类的成员变量,而该变量的名称存储在字符串中?
Is it possible to access the member variable of a class, where the variable's name is stored in a string?
class Test
{
public:
int test = 0;
}
string name = "test"; // let's assume we know test is an int.
是否有机会使用字符串获得测试的价值?
Any chance of getting the value of test, using the string?
不允许作弊:
enum vartype {
INT,
..
}
不强制类在 std :: map< string,std :: pair< vartype,void *>中注册其所有变量.>
.
欢迎所有其他技巧.
谢谢!
推荐答案
否.
为此,您需要在成员变量和您打算用来访问它们的字符串名称之间提供一些映射.
To do this, you need to provide some mapping between member variables and the string names by which you intend to access them.
这篇关于在运行时按其名称访问类成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文