所以我有这个:
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;
};
最佳答案
这是因为您在 push_back
调用中创建了一个临时 对象。一旦 push_back
函数返回,该对象就不再存在,并留下一个悬空指针。
您必须使用 new
创建一个新对象:
activeEnemies.push_back(new Spikey(_sceneManager, Ogre::Vector3(8,0,0)));
关于c++ - 如何访问在 std::vector 中存储为指针的接口(interface)实现对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16018478/