C ++从名称数组创建对象

时间:2017-08-13 22:16:16

标签: c++ arrays class object

这是我的第一个问题,我非常兴奋!

我想从类Person中创建很多对象,从字符串数组中获取每个对象的名称。

类似的东西:

class Person 
{
// bla bla bla
};

string listOfPersons [5000];

// here i will fill in the whole array with names

for (int i=0;i<5000);i++){
// here: create the objects with the name from the array
// like Person Mary.... Person John... Person... Patricia...

}

非常感谢!!

2 个答案:

答案 0 :(得分:0)

根据您更新的问题,您希望创建一个源文件,其中源代码中的这些变量名称基于数组中的名称。

在这种情况下,您需要编写一个单独的程序来以这种方式生成源代码。

这是一个如何做到这一点的简单模型

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
    fstream fstr("pablos.cpp",ios::out);
    string names[]={string("John"),string("Joe"),string("Sally")};

    if(fstr.is_open()){
        fstr <<     "#include <iostream>\n"  /* include what you need for the code */
                    "#include <Person.h>\n"
                    "int main(){\n";

        for(int i=0;i<3;i++){
            fstr << "   Person " << names[i]<<";\n";
        }

        fstr <<     "   return 0;\n"
                    "}\n";
        fstr.close();
    }

    return 0;
}

如果您运行此程序,您将生成一个新的源文件 Pablo.cpp ,如下所示:

#include <iostream.h>
#include <Person.h>
int main(){
   Person John;
   Person Joe;
   Person Sally;
   return 0;
}

您现在可以直接进一步编辑此源代码,或者在编译之前根据需要更改上面的生成程序(如果这恰好是目标)。我会留下您根据需要更新此来源。我不知道你为什么要在源代码中有5,000个不同命名的变量,但是可以这样做。

乍一看,根据评论,您似乎建议自行修改源代码,这不是事情的工作方式。需要编译源代码以便 act ,直接或间接执行。

原帖(供参考)

我认为你可能会让你的构造函数与你的数组混淆,或者你的字符串类与你的人类混在一起。

以下代码将创建两个独立的数组,每个数组包含5000个条目。如果您已经或者能够在您的Person类中添加setName方法,那么您可以分配所有5000个Person对象和5000个字符串。之后,使用名称填写您的字符串数组(看起来您已经有了这样做的方法)。最后,只需迭代您的Person数组并使用相应的字符串为每个条目调用setName方法。

class Person 
{
   // bla bla bla
   // includes a setName(string) method
   //
};

string arrayOfNames [5000];
Person arrayOfPersons [5000];

// after filling the whole array with names...
// (I assume this means arrayOfNames is filled in now..)  

for (int i=0;i<5000;i++){
    arrayOfPersons[i].setName(arrayOfNames[i]);  
}

答案 1 :(得分:0)

这可能是最愚蠢的答案,但如果我明白你想要做什么,无论如何这都是愚蠢的。

如果您想要的是声明Person类型的对象,并且Object的名称(这里我的意思是变量的名称)是从字符串设置的,我认为不可能。

listOfPersons[i]是一个字符串对象,可能等于程序中其他位置的另一个字符串对象(例如,您的数组中可以有两个“Johns”字符串)。

但是当你使用:

声明Person类型的变量时
Person person_name;

person_name是引用此Person类型变量的唯一ID,并且此id不能设置为programmaticaly,因为这不是字符串,是您在编写时编写它的人你的C ++代码文件。因此,如果您想要的是将对象声明为:

Person john;
Person patricia;
Person edward;
//...

除了手动之外你不能这样做。特别是不是来自字符串数组的 for 循环,因为这只是没有意义。

如果你想要的是使用字符串访问Person个对象,你想要使用的是map

using <map>

class Person 
{
// bla bla bla
};

string listOfPersons [5000];
std::map<string, Person> persons;

// here i will fill in the whole array with names

for (int i=0;i<5000);i++){
    Person temp;  // declare a temp Person object. Here you might instead want to use a constructor that you defined.
    persons[listOfPersons[i]] = temp; // Add the Person object into the map

    // This will be like doing persons["Patricia"] = temp;    
}

然后,当您想要访问对象时,您只需调用:

persons["name"];

用它做你想做的事。您还可以使用迭代器在整个人员地图上执行操作。