Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 虚拟功能-体系结构问题_C++_Object_Inheritance - Fatal编程技术网

C++ 虚拟功能-体系结构问题

C++ 虚拟功能-体系结构问题,c++,object,inheritance,C++,Object,Inheritance,我有: 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 g

我有:

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
类中创建一个函数,所以我假设他想让我在类
Game
中执行
虚拟的
函数。我这样做了,但我的问题是,如果我在类Barrel中根本不需要这个函数,那么这样做是否有意义,但通过使用虚拟函数,我可以在
Barrel
中编写a定义,而且我永远不会使用它。

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

Entity (renamed your Game)
  <- Creature (with getHP())
    <- Player (one of the implementations)
    <- Zombie
      <- SmallZombie
      <- BigZombie
  <- Barrel (without getHP())

恐怕这个问题太抽象了,回答不了。类名完全没有告诉我们它们的用途。我的猜测是
K
应该继承自
X
,所有这些
getHP()
重写都没有用(在
X
中应该只有一个
int-HP
成员,该类应该实现
getHP()
),但我对你的用例一无所知,也不知道你当初为什么选择这样做。我编辑了这篇文章,考虑到你问题的内容,你甚至不需要为僵尸和玩家设置不同的类。只要有一个类来处理有hp的东西,并用正确的数字来实例化它(例如,玩家100,僵尸20等等)。不需要从空的
游戏
类继承,也不需要多态函数。试着找出“类型的不同实例”和“不同类型”之间的区别。(顺便说一句,在99%的情况下,如果你的类有任何虚拟函数,它应该有一个虚拟析构函数。)@Yksisarvinen Nice pun:PRandom放在一边-确保你的基类型有一个虚拟析构函数。你也应该查一下为什么。
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()
};