简体   繁体   English

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

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

So I have this: 所以我有这个:

std::vector<EnemyInterface*> _activeEnemies;

where EnemyInterface looks like this: 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(){} 
};

I create a new enemy: 我创建了一个新敌人:

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

And I want to call the update function on every enemy, but it crashes: 我想对每个敌人调用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
    }

I can see the enemy on screen, but I cannot access it. 我可以在屏幕上看到敌人,但无法访问它。 Any help would be appreciated. 任何帮助,将不胜感激。

Spikey.h looks like this: 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;
};

It's because you create a temporary object in your push_back call. 这是因为您在push_back调用中创建了一个临时对象。 As soon as the push_back function returns that object is no more, and leaves you with a dangling pointer. push_back函数返回该对象时,该对象就不再存在,并留下一个悬空的指针。

You have to create a new object using new instead: 您必须使用new来创建一个新对象:

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

change 更改

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

to

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

And this is the correct call 这是正确的电话

(*it)->update(timeSinceLastFrame);

Your vector contains EnemyInterface* . 您的vector包含EnemyInterface*

So *it gives you EnemyInterface* - ie a pointer to EnemyInterface. 因此, *it为您提供了EnemyInterface* -即指向EnemyInterface的指针。 You can call a method using pointer to an object by using -> 您可以使用->使用指向对象的指针来调用方法

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

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