提问者:小点点

虚函数-体系结构问题


我有:

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
{
    
};

我的讲师说,gethpgethpk函数同时存在是没有意义的,所以他让我改变它,他建议在game类中做一个函数,所以我推测他想让我在game类中做virtual函数。 我这样做了,但我的问题是,如果我在类Barrel中根本不需要这个函数,那么这样做是否有意义,但是通过创建虚函数,我无论如何都要在Barrel中编写a定义,而我永远不会使用它。


共1个答案

匿名用户

下面是一个继承树,应该会有所帮助:

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()
};