我正在为大学课程做作业,我和我的伙伴遇到了问题。我们正在制作的程序是一个游戏。
我们有几个类,它们都继承自基类,称为 Creature。这些都是玩家需要处理的敌人,他们都运行自己的 AI。有 4 种不同类型的子类,都在命名空间 Creature(包括父级、Creature)中,其中一个类具有只有它需要的特殊功能。这个班级被称为兔子。
现在,我的工作是根据需要调用 AI 函数。问题是,当我要求游戏板告诉我我得到什么生物时,我并不总是知道我在呼唤什么类。
所有敌人都保存为指针,如下所示,在游戏板方块中:
struct Square
{
// Pointers to Morso class, where the enemy is saved
Creature::Creature* creature;
//Undeeded stuff removed
};
现在,这一切都很好,直到我们需要访问特殊功能。如果满足某些条件,Pupu会成倍增加。因此,在 Pupu 中,我需要调用的函数很少,以确保它正确执行。
然而,问题来了。
我打电话给我们的棋盘类,把我给它的坐标中的生物给我。
void GameEngine::GameEngine::runAI()
{
Creature::Creature* creature= NULL;
for(unsigned int y = 0; y < dimY; y++)
{
for(unsigned int x = 0; x < dimX; x++)
{
Coordinate target;
target.setX(x);
target.setY(y);
creature= board_->returnCreature(target);
//If there is a creature in the target, run its AI
if(creature!= NULL)
{
//If it is, check special procedures
if(creature->returnType() == "bunny")
{
bunnyReproduce(creature);
}
creature->ai();
}
}//for x
}//for y
}
现在, :
void GameEngine::GameEngine::bunnyReproduce(Ccreature::Creature* creature)
{
//Checks that it really is a bunny
if( creature->returnType() != "bunny"){ return; }
//Check is there another bunny near
creature->checkForMate();
}
问题是,在这一点上,生物不能调用 checkForMate,它是 Bunny 的公共成员,而不是 Creature。我们需要把虚函数变成Creature吗?
我尝试将 checkForMate 设置为 Creature::Bunny,但由于我尝试赋予它的原始值是 Creature 类,所以我不能这样做。我们是否需要在 Creature 类中创建一个空的虚函数,然后覆盖它 Bunnyclass?
我正在运行带有 QT 5.0.2 的 Qt Creator 2.7.0。