繁体   English   中英

如何访问存储为std :: vector中的指针的接口实现对象

[英]How to access an interface-implementing object stored as pointer in an std::vector

所以我有这个:

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函数,但是它崩溃了:

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

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

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

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

更改

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的指针。 您可以使用->使用指向对象的指针来调用方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM