有没有办法通过作为用户输入的字符串来创建类实例名称?

Is there any way to create a class instance name by a string taken as user input?

本文关键字:创建 字符串 实例 输入 用户 有没有      更新时间:2023-10-16

在C++中,我想创建一个类实例,其名称将是一个字符串作为输入。

请考虑以下代码段。

class my_class{
int a;
};
int main()
{
string name;
getline(cin, name); //let the input "tom"
my_class name; // expecting an instance of my_class named as tom
}

应该的,我得到了错误。有什么办法可以做到吗。

"有什么办法可以做到的" - 当然:

if (name == "foo") {
/* Create a foo */
} else if (name == "bar") {
/* Create a bar */
} // Etc ....