我试图让这个基于Zombie / Human agent的模拟运行,但我遇到了这些派生类(人类和僵尸)有父类“生物”的问题。我在“生物”中声明了3个虚函数,并且所有这三个虚函数都在“人类”和“僵尸”中重新声明和定义。但出于某种原因,当我让我的程序调用“new”来为Human或Zombie类型的对象分配内存时,它抱怨虚拟函数是抽象的。这是代码:
头:
class Creature
{
public:
virtual void Attack(Grid G) =0;
virtual void AttackCreature(Grid G, int attackdirection) =0;
virtual void Breed(Grid G) =0;
virtual ~Creature() {}
void Die();
void Move(Grid G);
int DecideSquare(Grid G);
void MoveTo(Grid G, int dir);
};
class Human : public Creature
{
public:
void Attack(Grid G);
void AttackCreature(Grid G, int attackdirection);
void Breed(Grid G); //will breed after x steps and next to human
int DecideAttack(Grid G);
};
class Zombie : public Creature
{
public:
void Attack(Grid G);
void AttackCreature(Grid G, int attackdirection);
void Breed(Grid G) {} //does nothing
int DecideAttack(Grid G);
};
CPP:
void Creature::Move(Grid G) {...}
int Creature::DecideSquare(Grid G) {...}
void Creature::MoveTo(Grid G, int dir) {...}
void Creature::Die() {...}
void Human::Breed(Grid G) {...}
int Human::DecideAttack(Grid G) {...}
void Human::AttackCreature(Grid G, int attackdirection) {...}
int Zombie::DecideAttack(Grid G) {...}
void Zombie::AttackCreature(Grid G, int attackdirection) {...}
void Zombie::Attack(Grid G) {...}
答案 0 :(得分:3)
在Creature
:
virtual void Breed() =0;
Human
中的:
void Breed(Grid G);
这些是不同的功能;后者不会超越前者。使Creature
中的纯虚函数取适当的参数。
Attack()
也是如此。
答案 1 :(得分:0)
声明了一个纯虚函数:virtual void Creature::Attack(Grid G)
但是派生类Human
没有实现,即没有定义void Human::Attack(Grid G)
方法,这就是为什么我得到了一个vtable
错误。它无法找到我承诺的函数的源代码。坏我!