c++ - vector 的对象如何访问 vector 元素

标签 c++ object vector element

这是一个模拟简单资源采集游戏的程序 机器人从 map 上收集资源并随机移动,每个机器人都做一些 Action 。 我的问题是我想从派生类机器人“RescueBot”中的类映射访问 vector 。 程序写在多个文件中,header.h、header.cpp、main.cpp

我有一个对象类型为“机器人”的 vector 和我的 header.h 文件的示例:

class Map{
  private:
    char World[20][20]; // The size of Map is 20 x 20
    vector<Robots*>RobotsVector; 
  public:
    Map();
    vector<Robots*>*getRobotsVector();

}

   // I access the vector with getRobotsVector() which belongs to Map class but returns 
   // Robot objects. Done this so i can access Robot objects within the Map class.

class Robots
{
private:
    //some variables

public:
    //some functions
    virtual void movement()=0; // this is the function that handles the robots moves
    virtual void action()=0; // this is the function that handles the robots actions
}

class RescueBot:public Robots{
   void movement();
   void action();
 //some unique RescueBot stuff here
}

这是来自 header.cpp 文件:

#include "header.h"
vector<Robots*>*Map::getRobotsVector(){return &RobotsVector;}

 //example of object creation and pushing into vector
void Map::creation(){
   for (int x=0;x<4;x++){
    getRobotsVector()->push_back(new RescueBot);
   }
}

void RescueBot::action(){
    //do stuff

 for(int i=0;i<Map::getRobotsVector()->size();i++){

       //Here is the problem. I cant get inside the for loop

      Map::getRobotsVector()->at(i)->setDamaged(false); //Changes a flag in other objects

   }
}

我试过使 Robots 类成为 Map 的派生类。之后,当我运行它时,我在 RescueBot::action 中访问的 vector 是空的,而实际 vector 中有对象。 如果我不派生它,它就不会编译。

我如何从 RescueBot::action() 中访问 vector ??

最佳答案

问题是您没有 Map 实例。

只有当 getRobotsVector 方法是 static 时,您当前调用它的方式才有效,但您不希望这样

当您将 Robots 类作为 Map 的派生类时它起作用的原因是因为 Map::getRobotsVector() 只是意味着您想在 RescueBot::action 函数运行的实例上调用 getRobotsVector 方法。

解决方案是通过引用将 Map 的实例传递给您的 action 函数。

这就是你的操作函数的样子:

void RescueBot::action(Map& map) {
    // Do whatever you want with the map here.
    // For example:
    map.getRobotsVector()->at(i)->setDamaged(false);
}

关于c++ - vector 的对象如何访问 vector 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643266/

相关文章:

javascript - 返回具有最多 props 的数组中的对象

javascript - 使用 JavaScript 和 lodash 汇总对象数组数据的最佳方法

c++ - 如何将 double vector 传递给构造函数,然后在子类中访问其数据(在 C++ 中)?

c++ - 在 vector 中读取和写入不同类型

c++ - 范围基数并插入 vector C++11

c++ - 在仿真代码中使用全局变量

Javascript 动态数组和对象

c++ - 如何使用 void `null` 或 `empty` 类元素扩展 C++ 结构/类

c++ - 如何创建#define值的 vector ?

string - 如何在 Rust 中将字符串转换为向量?