有没有办法将字符串或字符转换为类成员/成员函数以动态访问它们?
对于前。这个特定的代码,
#include <iostream>
#include <map>
using namespace std;
class agnt {
public:
int x, y;
agnt(int a=0, int b=0) : x(a), y(b) {}
};
int main() {
map<int,agnt> agntID;
agnt temp;
temp.x=1;
temp.y=5;
agntID[1]=temp;
for(char tmp='x'; tmp<'z'; tmp++) {
cout<<agntID[1].tmp<<'\n'; //Here I get the following error: tmp is
} //not a member of class agnt
}
有没有办法转换字符“tmp”,使其被识别为类成员?任何提示或解决方案将不胜感激。
C++没有任何内省 http://en.wikipedia.org/wiki/Type_introspection所以不,这是不可能的。
但是,您可以通过使用另一个来“破解”它std::map
包含名称作为键,值是对变量的引用:
agnt temp;
std::unordered_map<char, int&> variable_map = {
{ 'x', temp.x },
{ 'y', temp.y }
};
variable_map['x'] = 123;
std::cout << variable_map['y'] << '\n';
但这通常不值得,因为它需要更多的工作。特别是如果您想对多个变量执行此操作(因为每个结构变量都需要自己的映射)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)