這是一個模擬簡單資源收集遊戲的程序 機器人從地圖收集資源並隨機移動每一個執行一些操作。 我的問題是,我想訪問派生類的機器人「RescueBot」中的類映射向量。 該程序被寫入在多個文件中,header.h,header.cpp,main.cpp中矢量對象如何訪問矢量元素
我有對象的矢量型「機器人」和我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
}
}
我試圖使機器人類derivered類地圖。之後,當我運行它時,我在RescueBot :: action中訪問的矢量是空的,而實際矢量中有對象。 如果我不使它派生它不編譯。我如何從RescueBot :: action()內部訪問vector?
它不能,除非你通過矢量對象的構造函數或指針設置爲您添加到每個對象的矢量那個矢量。一般來說,沒有一個是一個特別好的主意。 – dasblinkenlight
你對它的看法是錯誤的。如果RescueBot需要修改Map,那麼它需要將Map作爲參數,無論是在構造函數還是在動作命令中(我個人更喜歡動作命令)。 – IdeaHat