簡體   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