C++ C++;如何使用数组的元素调用类
我正在创建一个神奇宝贝战斗模拟器,我想知道是否可以使用数组元素调用类C++ C++;如何使用数组的元素调用类,c++,arrays,class,C++,Arrays,Class,我正在创建一个神奇宝贝战斗模拟器,我想知道是否可以使用数组元素调用类 #include <iostream> #include <time.h> #include <string> using std::cout; using std::endl; using std::string; string PokémonArray[] = { "Pikachu","Pidgey" }; class Pokémon { public: string ba
#include <iostream>
#include <time.h>
#include <string>
using std::cout;
using std::endl;
using std::string;
string PokémonArray[] = { "Pikachu","Pidgey" };
class Pokémon {
public:
string basic_attack;
int basic_attack_dmg;
string getBasicAttackName() { return basic_attack; }
Pokémon() { ; }
};
class Pikachu : public Pokémon {
public:
Pikachu(){ basic_attack = "Whatever"; }
};
int main(){
int random_num;
string randEnemy;
srand(TIME(NULL));
random_num = rand() % 2; //Generates a random number between 0 and 1
randEnemy = PokémonArray[random_num]; //Sets randEnemy to be equal to the element 0 or 1 (generated above) of the array
(randEnemy) enemy; //Try to create the object 'enemy' calling a class using an element of the array
}
#包括
#包括
#包括
使用std::cout;
使用std::endl;
使用std::string;
字符串PokémonArray[]={“Pikachu”,“Pidgey”};
神奇宝贝班{
公众:
串基攻击;
int basic_attack_dmg;
字符串getBasicTackName(){return basic_attack;}
神奇宝贝(){;}
};
皮卡丘类:公共神奇宝贝{
公众:
皮卡丘(){basic_attack=“Whatever”}
};
int main(){
int随机数;
敌人;
srand(时间(空));
random_num=rand()%2;//生成一个介于0和1之间的随机数
RandDebuy=PokémonArray[random_num];//将RandDebuy设置为等于数组的元素0或1(在上面生成)
(RANDENGINE)敌人;//尝试使用数组元素创建调用类的对象“敌人”
}
如何使用同名数组的元素调用该类?可以将口袋妖怪存储在数组中
Pokemon PokémonArray[152];
然后在需要时直接调用它们的函数
randEnemy = PokémonArray[random_num];
randEnemy.basicAttack();
直接回答你的问题-是的,你可以,但是你需要很多if/else语句,你必须使用多态基
Pokemon* pokemon = nullptr;
if(randEnemy == "Pikachu")
pokemon = new Pikachu;
else if (randEnemy == "Raichu")
pokemon = new Raichu;
else if...
这种模式被称为“工厂方法”或“虚拟构造函数”。您可以(也应该)将口袋妖怪
直接存储在数组中,但它不会像另一个答案指定的那样简单,因为口袋妖怪
实例显然是多态的。因此,您需要存储一个指向Pokemon
实例的指针
最好是智能指针(用于自动销毁)。根据用途,它可以是:
std::vector<std::unique_ptr<Pokemon> > PokemonArray;
std::vector口袋妖怪;
或
std::vector口袋妖怪;
(取决于指针实例是否可以由多个所有者拥有)
或者是一个简单的数组,但我通常更喜欢
std::vector
为什么你要用字符串数组而不是口袋妖怪数组?你是想根据随机数生成一个随机的敌人吗?意思是只有两种敌人?
std::vector<std::shared_ptr<Pokemon> > PokemonArray;