在 c++ 中动态创建对象
Dynamically create objects in c++?
看看这段代码,它有一个类,当创建一个新对象时,它会给它一个随机数,用于 'lvl' 在 1 到 100 之间。在类之后,我使用类实例定义一些对象。
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
class newPokemon {
public:
int lvl;
newPokemon() {
lvl = (rand() % 100 + 1);
};
void getLevel() {
cout << lvl << endl;
};
};
newPokemon Gengar;
newPokemon Ghastly;
newPokemon ayylmao;
};
我接下来要做的是通过要求它们提供名称来允许使用来定义新的口袋妖怪(对象)。但是,这意味着我需要动态创建对象。例如
程序要求用户输入名称
然后将名称保存为类新口袋妖怪
的对象程序可以使用该名称来运行类中的其他函数,例如 getLevel。
我该怎么做?当然,我知道我不能像硬编码那样做,因为我不能将用户输入作为变量名称引用,但是有没有办法通过操纵指针或其他东西来完成我所要求的?
使用 std::map
根据对象的名称来保存对象:
std::map<std::string, newPokemon> world;
必须确保对象在创建后立即添加到map
。
std::string name;
... // ask the user for a name
world[name] = newPokemon();
std::cout << "Your level is " << world[name].getLevel() << 'n';
您可能只希望每个口袋妖怪都有一个name
属性(成员变量/字段)。只需制作一堆填写名称的口袋妖怪。
相关文章:
- 有没有办法基于文本文件动态创建对象?
- 如何创建一个动态数组,该数组可以保存从C++中派生的同一基类的所有不同对象
- 创建一个动态2D数组来存储类对象
- 创建对象的动态数组,删除对象并释放C++内存
- 动态创建对象并将其内存设置为 0
- 如何多态地创建对象的动态数组
- 在循环中动态创建对象
- 从QML动态创建C++对象
- 如何创建指向动态分配对象的指针向量
- 存储动态创建对象的列表/向量的最佳方法是什么
- 用c++动态创建对象
- 创建对象的动态数组
- 在 c++ 中动态创建对象
- 如何在不使用默认构造函数的情况下通过new创建对象的动态大小数组
- C++创建对象的动态数组
- 如何创建一个动态分配的c++对象及其指针
- 如何动态创建对象
- 如何在没有动态内存分配的情况下创建对象数组
- c++:在构造函数调用中作为参数创建的动态分配对象会发生什么?
- 在C++中动态创建对象