【问题标题】:How to access an interface-implementing object stored as pointer in an std::vector如何访问作为指针存储在 std::vector 中的接口实现对象
【发布时间】:2013-04-07 18:17:26
【问题描述】:

所以我有这个:

std::vector<EnemyInterface*> _activeEnemies;

EnemyInterface 如下所示:

#include "Ogre.h"

class EnemyInterface{
public:
  virtual void update(const Ogre::Real deltaTime) = 0;
  virtual void takeDamage(const int amountOfDamage, const int typeOfDamage) = 0;
  virtual Ogre::Sphere getWorldBoundingSphere() const = 0;
  virtual ~EnemyInterface(){} 
};

我创造了一个新的敌人:

// Spikey implements EnemyInterface
activeEnemies.push_back( (EnemyInterface*) &Spikey(_sceneManager, Ogre::Vector3(8,0,0)) );

我想对每个敌人调用更新函数,但它崩溃了:

// update enemies
for (std::vector<EnemyInterface*>::iterator it=_activeEnemies.begin(); it!=_activeEnemies.end(); ++it){
        (**it).update(timeSinceLastFrame); // Option 1: access violation reading location 0xcccccccc
        (*it)->update(timeSinceLastFrame); // Option 2: access violation reading location0xcccccccc
    }

我可以在屏幕上看到敌人,但我无法访问它。 任何帮助将不胜感激。

Spikey.h 看起来像这样:

#include "EnemyInterface.h"

class Spikey: virtual public EnemyInterface{
private:
int thisID;
static int ID;

Ogre::SceneNode* _node;
Ogre::Entity* _entity;
public:
Spikey(Ogre::SceneManager* sceneManager, const Ogre::Vector3 spawnPos);

// interface implementation
virtual void update(const Ogre::Real deltaTime);
virtual void takeDamage(const int amountOfDamage, const int typeOfDamage);
virtual Ogre::Sphere getWorldBoundingSphere() const;
};

【问题讨论】:

    标签: c++ interface iterator stdvector


    【解决方案1】:

    这是因为您在push_back 调用中创建了一个临时 对象。只要push_back 函数返回该对象,该对象就不再存在,并留下一个悬空指针。

    您必须改为使用new 创建一个新对象:

    activeEnemies.push_back(new Spikey(_sceneManager, Ogre::Vector3(8,0,0)));
    

    【讨论】:

    • 谢谢你,@Joachim Pileborg!
    【解决方案2】:

    改变

    activeEnemies.push_back( (EnemyInterface*) &Spikey(_sceneManager, Ogre::Vector3(8,0,0)) );
    

    activeEnemies.push_back( new Spikey(_sceneManager, Ogre::Vector3(8,0,0)) );
    

    这是正确的调用

    (*it)->update(timeSinceLastFrame);
    

    您的vector 包含EnemyInterface*

    所以*it 给你EnemyInterface* - 即指向 EnemyInterface 的指针。你可以通过-&gt;使用指向对象的指针来调用方法

    【讨论】:

    • 但是由于Spikey 继承自EnemyInterface 是不是演员表是多余的?
    • @AdriC.S.会更新。错过了 - 更多地关注 &temp 的东西。谢谢
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 2017-01-25
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多