c++ - 如何访问在 std::vector 中存储为指针的接口(interface)实现对象

标签 c++ interface iterator stdvector

所以我有这个:

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/

相关文章:

android - fragment 可以实现其父 Activity 的两个接口(interface)吗?

delphi - for在TObjectList中怎么办?

c++ - 为什么 C++ STL 中的算法、迭代器和容器是分离的

c++ - 使用 pthread 创建 mandelbrot 图像

c++ - 为什么我的复制赋值运算符从未被调用过?

c# - 这是接口(interface)的错误使用吗?

java - 如何双向迭代列表?

c++ - 如何初始化静态成员变量 "dynamically"?

c++ - 静态代码分析器 : unmanaged C++ Visual Studio 2008

java - 接口(interface)之间的转换