2016-01-21 84 views
0

看看这段代码,它有一个类,当创建一个新对象时,它会给它一个1到100之间的'lvl'的随机数。在类之后,我使用类实例定义了一些对象。在C++中动态创建对象?

#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; 
}; 

我想接下来要做的是允许通过询问他们的名字来定义新的小宠物(对象)。这意味着,但是,我需要动态地创建对象。例如,

程序要求用户输入一个名称,然后
名称保存为从类newPokemon
程序可以使用该名称从类运行的其他功能,如getLevel的对象。

我该如何做到这一点?当然,我知道我不能像硬编码那样做,因为我不能将用户输入作为变量名引用,但是有什么方法可以通过操作指针或其他方法来完成我所要求的操作吗?

+0

像['vector'](http://en.cppreference.com/w/cpp/container/vector)的任何种类的可扩展集合。这将意味着每个变量不会拥有自己的名字,而是某种类型的索引。 –

+0

如果我理解你是对的,你可以使用[std :: map](http://en.cppreference.com/w/cpp/container/map)或[std :: unordered_map](http:// en。 cppreference.com/w/cpp/container/unordered_map) – MikeMB

+0

我们知道;向我们展示实际的代码。你想要的是创建一个函数,该函数返回一个'Pokemon',它接受一个字符串类型的参数,这个名字就是名字。 – Poriferous

回答

1

你可能只是想让每个口袋妖怪都有一个name属性(成员变量/字段)。只是做了一堆口袋妖怪已填充名字

3

使用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';