我正在为大学类(class)做作业,我和我的搭档遇到了问题。我们正在制作的程序是一个游戏。
我们有几个类,它们都继承自名为 Creature 的基类。这些都是玩家需要对付的敌人,他们都有自己的 AI。有 4 种不同类型的子类,都在命名空间 Creature(包括 parent,Creature)中,其中一个类具有仅它需要的特殊功能。这个类叫做 Bunny。
现在,我的工作是根据需要调用 AI 函数。问题是,当我要求游戏板告诉我我得到什么生物时,我并不总是知道我在呼唤什么类。
所有敌人都像这样保存为指针,在游戏板正方形中:
struct Square
{
// Pointers to Morso class, where the enemy is saved
Creature::Creature* creature;
//Undeeded stuff removed
};
现在,一切都很好,直到我们需要访问特殊功能。如果满足某些条件,Pupu 将成倍增加。因此,在 Pupu 中,我需要调用几个函数来确保它正确执行。
但是,问题来了。
我调用我们的 board 类来给我坐标中的生物。
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 的公共(public)成员,但不是 Creature。需要把虚函数做成Creature吗?
我尝试将 checkForMate 变成 Creature::Bunny,但由于我尝试赋予它的原始值是 Creature 类,所以我不能这样做。我们是否需要在 Creature 类中创建一个空虚函数,然后在 Bunny 类中重写它?
我正在运行带有 QT 5.0.2 的 Qt Creator 2.7.0。
最佳答案
您应该添加 virtual函数 reproduce
到 Creature
类,并在 Bunny
或您以后可能添加到游戏中的任何其他生物中实现它。这样任何生物都会以自己的方式繁殖自己。在这种情况下你甚至不需要检查生物类型。因为如果你有一些不可复制的生物,你可能只是将 reproduce
实现为什么都不做的空方法。
关于c++ - 访问子函数,同时使用父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16212307/