c ++多级继承不起作用

Mol*_*erC 3 c++ inheritance

我似乎无法让多级继承函数调用正常工作.对于我的结构,我有一个"实体"作为主要的超级类

实体 - >子弹,代理

特工 - >球员,敌人

敌人 - > BasicEnemy

在每个中我都有一个"更新"功能

class Entity
{
public:
    Entity();
    virtual ~Entity();
    //stuff
    virtual Bullet update(float deltaTime);
 }


class Agent : public Entity
{
public:
    Agent();
    virtual ~Agent();

    virtual Bullet update(float deltaTime);

class Player : public Agent
{
public:
    Player();
    ~Player();

    Bullet update(float deltaTime) override;

class Enemy : public Agent
{
public:
    Enemy();
    virtual ~Enemy();

    virtual Bullet update(float deltaTime);

class BasicEnemy : public Enemy
{
public:
    BasicEnemy();
    ~BasicEnemy();

    Bullet update(float deltaTime) override;
Run Code Online (Sandbox Code Playgroud)

我创建玩家,敌人和子弹对象然后将它们传递给实体向量,但每当我打电话时

Entity entity = entities[i];
entity.update(deltaTime);
Run Code Online (Sandbox Code Playgroud)

它只进入"代理"更新功能,如果我使代理更新功能纯虚拟,它只是进入实体更新功能,为什么玩家和敌人更新功能不会覆盖基本功能?

Tib*_*ács 5

这是因为您将对象存储在向量中.你应该存储对象的指针.

详细信息:在C++中,如果将Agent 对象强制转换为Entity 对象,则会丢失有关该对象的所有信息,Agent并且新对象将是真实的Entity.即你松散了多态行为.

当您使用Entity对象创建了一个向量并Agent在其中推送和对象时,会发生这种情况,因为存储的对象将是纯Entity对象.

在C++中,引用和指针保持多态性.因此,要解决此问题,您应该创建一个指针向量:

std::vector< Entity* > entities;
entities.push_back( new Agent( ) );
entities[ 0 ]->update( 5); // Agent::update will be called
Run Code Online (Sandbox Code Playgroud)

  • 另见:http://stackoverflow.com/questions/274626/what-is-object-slicing (2认同)