gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:25:00 25 4
gpt4 key购买 nike

这是一个模拟简单资源采集游戏的程序机器人从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com