Accessing a class member variable by its name at runtime [duplicate]

此生再无相见时 提交于 2019-12-31 05:19:10

问题


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?

One bit of cheating not allowed:

enum vartype {
INT,
..
}

No forcing the class to register all its variables in a std::map<string, std::pair<vartype, void*> >.

All other tricks welcome.

Thanks!


回答1:


No.

To do this, you need to provide some mapping between member variables and the string names by which you intend to access them.




回答2:


In the realm of really ugly kluges, you could build the program with debug information and have it use that to find the location of the variable in the same way a debugger would. But other than that, you're out of luck. C++ doesn't do reflection.




回答3:


About why it's not available in C++ and an alternative: http://en.allexperts.com/q/C-1040/eval-function-javascript-C.htm

It's possible in MATLAB though... As a very simple example, if you have a matrix updation to do, which goes like:

M1=1;
M2=2;
M3=3;

And you would prefer that the variable names could be altered so that you could use a for loop, then it can also be done this way:

for i=1:3
eval(['M' num2str(i) '=' num2str(i)]);
end

I used to do this in Actionscript. Was really glad to find that it's available in Matlab too



来源:https://stackoverflow.com/questions/4242910/accessing-a-class-member-variable-by-its-name-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!