我有:
class Game
{
};
class Zombie :public Game
{
public:
virtual int getHP() const=0;
};
class Zombiesmall : public Zombie
{
int HPy=30;
public:
int getHP() const;
};
class Zombiebig : public Zombie
{
int HPz=20;
public:
int getHP() const;
};
class Player : public Game
{
int hpk=100;
public:
int getHPK() const;
};
class Barrel: public Game
{
};
我的讲师说,getHP
和getHPK
的功能是不存在的,因此他要求我更改它,并建议在Game
中使用一个功能。类,所以我假设他要我在类virtual
中执行Game
的功能。我这样做了,但是我的问题是,如果我根本不需要在Barrel类中使用此函数,是否有这样做的意义,但是通过使虚函数使我无论如何都可以在Barrel
中编写一个定义,并且我永远不会使用它。
答案 0 :(得分:0)
这是一个应该帮助的继承树:
Entity (renamed your Game)
<- Creature (with getHP())
<- Player (one of the implementations)
<- Zombie
<- SmallZombie
<- BigZombie
<- Barrel (without getHP())
在C ++中:
class Entity { // base for other classes
public:
virtual ~Entity() = default;
};
class Creature : public Entity { // has getHP()
public:
virtual int getHP() const = 0;
};
class Player : public Creature { // is-a Creature => must implement getHP()
private:
int hp = 100;
public:
int getHP() const override {
return hp;
}
};
// similar for zombies
class Barrel : public Entity { // not a Creature => doesn't have getHP()
};