如何在 c++ 中动态创建(游戏角色)类的多个对象
How do I create multiple objects of a (game character) class dynamically in c++
我必须修改我的程序并创建一个新的(Gamefigures)类,我当前的类(Rabbit和Hedg)从中继承。代码是一个小游戏,两只动物比赛直到达到目标,但在第二个任务中,我必须确保这些动物的多次迭代可以比赛。(例如 5 对 5 或 X 对 X)。我可以将一些变量或方法移动到Gamefigures
类中。两种动物都使用不同的规则来行走。如何创建一个新类,该类动态创建同一类的多个对象,我的当前类从中继承?
我尝试使用新表达式创建一个新对象,但我不知道这是否是正确的做法。
我试过了:
Hedg* nHedg = new Hedg[numFigures];
这是我的其余代码:
class Hedg: public Gamefigures
{
private:
int salat = 1;
protected:
int position1 = 0;
public:
bool turn(int fields)
{
int counter = 10;
if (fields < 11)//Less than 10 fields
{
while ((counter > 0))
{
if (counter < fields)//max 10 fields
{
fields = counter;
}
position1 += fields;//walk
counter -= fields;
if (counter <= 0)
{
salat = 0;
}
}
getSalat();
return true;
}
else
return false;
}
Hedg()
{
}
int getPosition1()
{
return position1;
}
int getSalat()
{
return salat = 1;
}
int getStock1()
{
return salat;
}
~Hedg()
{
}
};
class Game :public Hedg, public Rabbit
{
private:
int goal = 0;
int numFields = 0;
protected:
Rabbit theRabbit;
Hedg theHedg;
public:
Game();
Game(int numFields);
int getGoal();
int dice();
void doyourturn();
bool getStand();
~Game();
};
以下是错误消息:
Error code C4430 missing typespecifier
我认为多态性是你的用例所需要的,它将解决你的问题。
假设您有一个动物的基类:
class Animal
{
// ...
// Create all the (pure) virtual methods to be redefined by a derived class
virtual void walk() = 0; // For example
};
然后你定义你的两种特定的动物,兔子和刺猬:
class Rabbit : public Animal
{
// ...
// Redefine here the (pure) virtual methods of Animal for a Rabbit
void walk() override;
};
class HedgeHog : public Animal
{
// ...
// Redefine here the (pure) virtual methods of Animal for a HedgeHog
void walk override;
};
您可以使用多态性来处理您的动物列表:
std::vector<Animal*> race_competitors;
race_competitors.push_back(new Rabbit);
race_competitors.push_back(new HedgeHog);
这样,当您在竞争对手身上调用walk()
方法时,它将自动执行相应动物的正确行走规则。
当然,在比赛结束时,不要忘记delete
载体的内容,因为动物是用new
创建的("手动"分配的内存,在堆上)。
仅供参考,Game
类不必继承Rabbit
和HedgeHog
,它只需要知道他们是类成员,或者更好的是,将std::vector<Animal*>
存储为竞争对手列表。
我希望它能帮助您改进设计并解决您的问题。
相关文章:
- 开发C++/地图中的控制台角色扮演游戏
- 将四元数旋转的游戏对象旋转另一个四元数时出现问题
- 我的角色向左走,但不向右走(主机游戏)
- 在游戏循环中创建类对象
- 在C++中,我的主机游戏角色在游戏场数组内移动时不会停止
- 如何在 c++ 中动态创建(游戏角色)类的多个对象
- 无法访问/存储地图中的游戏状态对象
- 在基于文本的游戏中,如何将对象放置在房间内?
- "游戏对象":没有合适的默认构造函数可用
- 使用什么数据结构来存储基于游戏对象的二维单元地图?
- 游戏引擎:Dynamic_cast-对象类不是多态类型
- C++ 确定类是否可以使用对象 - 文本 RPG 游戏
- 如何与时间连续创建对象?C 游戏
- 如何处理C 游戏中的许多对象
- 使用Lua定义C++游戏中对象的变量
- 基于文本的角色扮演游戏拖放和保留物品功能
- 程序语言和面向对象语言的游戏设计差异
- 重新启动游戏并重新构造全球对象
- 如何有效地将游戏对象存储在四叉树中
- 游戏项目的多对象类型容器或动态铸造