将字符串转换为变量名称或变量类型 [英] Convert string to variable name or variable type

查看:154
本文介绍了将字符串转换为变量名称或变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过执行以下操作将字符串转换为变量(反之亦然):

Is it possible to convert strings into variables(and vise versa) by doing something like:

makeVariable("int", "count");

string fruit;
cin >> fruit;    // user inputs "apple"
makeVariable(fruit, "a green round object");

,然后可以通过执行以下操作来访问它:

and then be able to just access it by doing something like:

cout << apple; //a green round object

提前感谢!

推荐答案

不,这是不可能的。这种功能在像Ruby和Python这样的脚本语言中很常见,但是C ++的工作方式与那些非常不同。在C ++中,我们在程序的工作中,我们可以在编译时。有时我们可以在运行时做事情,甚至好的C ++程序员会在编译时找到一种方法来完成工作。

No, this is not possible. This sort of functionality is common in scripting languages like Ruby and Python, but C++ works very differently from those. In C++ we as much of the program's work as we can in compile time. Sometimes we can do things at runtime, and even then good C++ programmers will find a way to do the work as early as at compile time.

如果你知道你要创建一个变量,然后立即创建它:

If you know you're going to create a variable then create it right away:

int count;

你可能不知道的时间是变量的值,所以你可以延迟运行时间:

What you might not know ahead of time is the variable's value, so you can defer that for runtime:

std::cin >> count;

如果你知道你需要一个变量集合,创建地图或向量:

If you know you're going to need a collection of variables but not precisely how many of them then create a map or a vector:

std::vector<int> counts;

请记住,变量的名称只是一个名称;一种方法让你以后参考变量。延迟将变量的名称分配给运行时并不是很有用,即使它是可能的(而不是)。所有这一切都是让你的代码更复杂,你的程序更慢。

Remember that the name of the variable is nothing but a name; a way for you to refer to the variable later. It is not useful to defer assigning the name to the variable to runtime, even if it were possible (and it's not). All that would do is make your code more complex and your program slower.

这篇关于将字符串转换为变量名称或变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆