C ++:变量值作为变量

时间:2012-05-10 04:15:36

标签: c++

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

在php中我们可以通过其他变量的值来创建/打印变量。 像这样。

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

我怎样才能在c ++中解决这个问题?

3 个答案:

答案 0 :(得分:3)

你不能。

模仿这种(很好)的唯一方法是使用map

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

从另一个角度来看,它只是间接性,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'