gpt4 book ai didi

c++ - 在 C++ 中将字符串/字符转换为类成员/方法

转载 作者:太空狗 更新时间:2023-10-29 20:42:12 25 4
gpt4 key购买 nike

有没有办法将字符串或字符转换为类成员/成员函数以动态访问它们?

例如。这个特定的代码,

 #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++ 没有任何 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';

不过这通常不值得,因为它需要更多的工作。特别是如果您想对多个变量执行此操作(因为每个结构变量都需要自己的映射)。

关于c++ - 在 C++ 中将字符串/字符转换为类成员/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19557881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com