Clo*_*all 0 c++ iterator interface stdvector
所以我有这个:
std::vector<EnemyInterface*> _activeEnemies;
Run Code Online (Sandbox Code Playgroud)
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(){}
};
Run Code Online (Sandbox Code Playgroud)
我创造了一个新的敌人:
// Spikey implements EnemyInterface
activeEnemies.push_back( (EnemyInterface*) &Spikey(_sceneManager, Ogre::Vector3(8,0,0)) );
Run Code Online (Sandbox Code Playgroud)
我想在每个敌人身上调用更新功能,但它崩溃了:
// 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
}
Run Code Online (Sandbox Code Playgroud)
我可以在屏幕上看到敌人,但我无法访问它.任何帮助,将不胜感激.
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;
};
Run Code Online (Sandbox Code Playgroud)
这是因为你在通话中创建了一个临时对象push_back.一旦push_back函数返回该对象就不再存在,并为您留下悬空指针.
您必须使用以下方法创建新对象new:
activeEnemies.push_back(new Spikey(_sceneManager, Ogre::Vector3(8,0,0)));
Run Code Online (Sandbox Code Playgroud)