在运行时c ++创建具有特定对象名称的未知数量的对象

Str*_*ght 1 c++ scope loops object-lifetime

我想在运行时在main方法中创建一个未知数量的对象,每个对象都有一个特定的对象名.在程序结束之前,对象应该存在(main-method结束).请注意,在我的情况下,对象是Fields.

我想过这样的解决方案:

for ( i=1 ; i <= NumberOfObjects ; i++)
{

if (i==1)
{
MyClass *ObjectName1 = new MyClass();

}

if (i==2)
{
MyClass *ObjectName2 = new MyClass();

}

.   //more if statements for more objects
.
.

} //for loop closed
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 我不认为这个解决方案是好的,因为创建的对象的数量仍然限于for循环中的if语句.更好的解决方案?

  2. 循环中指针的范围:当退出if块时,指针超出范围.之后如何访问"新"创建的对象?

con*_*t3d 6

编译代码后删除命名变量,之后对您没有任何意义.

看起来你需要一个查找表,使用带有字符串键的std :: map或std :: unordered_map作为对象的名称.

std::map<std::string, MyClass*> variablesTable;
for ( i=1 ; i <= NumberOfObjects ; i++)
{
    std::ostringstream oss << "name" << i;
    variablesTable[oss.str()] = new MyClass();    //you actually need to check if it exists, otherwise will be overwritten.
}    
Run Code Online (Sandbox Code Playgroud)

好像你希望每个创建的每个对象都运行一个单独的代码,你可以有一个函数对象表(或者只是存储在一个元组中),就像这样 std::map<std::string, std::<MyClass, Func>>.

如果你想查找只是使用,

MyClass* object = variablesTable[strName];
object->CallFunction();
Run Code Online (Sandbox Code Playgroud)

PS hash_maps的一个已知技巧是在构建项目之前运行脚本以将任何文字字符串转换为int,因为比较int比字符串更快.至少我知道这是在Uncharted系列中使用的(但与你的情况几乎没有关系).