在运行时创建具有不同名称的对象

Creating Objects with Different Names at runtime?

本文关键字:对象 运行时 创建      更新时间:2023-10-16

我有一个班叫大学。我希望创建班级系的对象,而班级大学有一个向量类型系。我的程序是读取一个文件,并根据给定的命令,调用不同的函数。我的程序是制作类Department的多个对象,并将它们放入大学类中名为Departments的向量中。

我不知道如何使Department类型的多个对象具有不同的名称。

bool University::CreateNewDepartment(string depName, string depLoc, long depChairId)
{
if (depChairId == 0)
//Department ___(depName, depLoc, depChairId);
//Departments.pushback(___)
return true;
}

___是正在创建的部门对象名称的占位符。我如何使它在每次创建时都有不同的名称?非常感谢。

您将变量名称与数据(即此类变量中包含的内容)混合在一起。

变量名并不意味着什么,它只是用来引用代码中某个特定的占位符,而数据是您通常修改的内容。

因此:

Department department = Department(depName, location, chairID);
departments.push_back(department);

非常好。department只是函数内部正在创建的部门的本地名称。depName是另一个变量,它将包含真实名称,即std::string(例如"Nice Department"),它是真实数据。

定义Department如下:

class Department 
{
public:
    Department(const std::string& name, const std::string& location, long chairId) 
        : name_(name)
        , location_(location)
        , chairId_(chairId)
    {
    }
    // probably want accessors to get the variables ... 
private:
    std::string name_;
    std::string location_;
    long chairId_;
};

然后在University::CreateNewDepartment中进行

departments.push_back(Department(depName, depLoc, depChairId));

您的University类需要有一个名为departmentsstd::vector<Department>成员,等等。