在 c++ 中动态创建对象

Dynamically create objects in c++?

本文关键字:创建对象 动态 c++      更新时间:2023-10-16

看看这段代码,它有一个类,当创建一个新对象时,它会给它一个随机数,用于 '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属性(成员变量/字段)。只需制作一堆填写名称的口袋妖怪。