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