在运行时创建具有不同名称的对象
Creating Objects with Different Names at runtime?
我有一个班叫大学。我希望创建班级系的对象,而班级大学有一个向量类型系。我的程序是读取一个文件,并根据给定的命令,调用不同的函数。我的程序是制作类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
类需要有一个名为departments
的std::vector<Department>
成员,等等。
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 通过switch和static_cast访问多态对象的运行时类型
- "main"函数堆栈中的对象在第一个任务运行时被覆盖 (FreeRTOS)
- cout 新创建的对象引发运行时错误
- C++,如何根据运行时条件构造引用不同 istream 对象的对象?
- 创建 QtChart 对象会在运行时创建EXC_BAD_ACCESS错误
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 如何在运行时创建和命名对象?
- C++ 在运行时选择一个随机对象
- 在运行时 c++ 更改用类对象填充的数组的大小
- C++ 在运行时获取具有 ID 的对象
- 如何在运行时从 c++ 中的 DLL 文件创建对象?
- 为什么 Z3 BitVec 对象没有运行时大小信息?
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 是否有任何可能的方法将事件(自定义)附加到在运行时创建的对象?[C 构建器]
- 在C 中运行时从指针访问对象实例
- 如何在运行时指定对象类型
- 根据用户的输入在运行时创建对象
- 为什么C++不按运行时类型销毁对象?
- 根据用户配置在运行时链接共享对象