Access variable value using string representing variable#39;s name in C++(在 C++ 中使用表示变量名称的字符串访问变量值)
问题描述
如果标题不清楚,我会尽量澄清我的问题:
If the title was not clear, I will try to clarify what I am asking:
假设我有一个名为 counter 的变量,我知道我可以通过执行以下操作来查看其当前值:
Imagine I have a variable called counter, I know I can see its current value by doing something like:
std::cout << counter << std::endl;
但是,假设我有很多变量,并且直到运行时我不知道要查看哪些变量.
However, assume I have lots of variables and I don't know which I'm going to want to look at until runtime.
有谁知道我可以通过使用变量名称获取变量值的方法,例如:
Does anyone know a way I can fetch the value of a variable by using its name, for example:
std::cout << valueOf("counter") << std::endl;
我觉得能够做到这一点可能会使调试大型复杂项目变得更容易.
I feel being able to do this might make debugging large complex projects easier.
提前感谢您的时间.
更新:所提供的所有答案都是有效且有用的,但重点是 C++ 中不存在反射(阅读推荐的链接后很清楚原因).
Update: All the answers provided are valid and useful, however the main point is that reflection does not exist in C++ (and after reading the link recommended it is clear why).
推荐答案
如前所述,您正在寻找 C++ 中的反射.它没有那个,这个答案解释了原因.
As has been mentioned, you are looking for reflection in C++. It doesn't have that, and this answer explains why.
这篇关于在 C++ 中使用表示变量名称的字符串访问变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中使用表示变量名称的字符串访问变量值
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
