C++:变量中的值作为变量

C++ : value from variable as variable

本文关键字:变量 C++      更新时间:2023-10-16

如何在 C++ 中从其他变量的值打印变量我只是 C++ 的新手。

在PHP中,我们可以通过其他变量的值来制作/打印变量。喜欢这个。

$example = 'foo';
$foo = 'abc';
echo ${$example}; // the output will 'abc'

如何在 C++ 中解决此问题?

你不能

模拟这一点(嗯)的唯一方法是使用地图

按名称获取变量/成员称为反射/内省。

C++中没有反射机制,基本上你不能这样做。

从另一个角度来看,它只是间接的,C++广泛使用。 C++中类似的例子可能是...

using namespace std;
string foo = "abc";
string* example = &foo;
cout << *example << endl;  // The output will 'abc'

。或使用引用而不是指针...

using namespace std;
string foo = "abc";
string& example = foo;
cout << example << endl;  // The output will 'abc'