2013-12-17 179 views
2

這是一個模擬簡單資源收集遊戲的程序 機器人從地圖收集資源並隨機移動每一個執行一些操作。 我的問題是,我想訪問派生類的機器人「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?

+0

它不能,除非你通過矢量對象的構造函數或指針設置爲您添加到每個對象的矢量那個矢量。一般來說,沒有一個是一個特別好的主意。 – dasblinkenlight

+1

你對它的看法是錯誤的。如果RescueBot需要修改Map,那麼它需要將Map作爲參數,無論是在構造函數還是在動作命令中(我個人更喜歡動作命令)。 – IdeaHat

回答

1

問題是您沒有Map實例。

你調用它目前只能如果getRobotsVector方法是static的工作方式,但你不希望

時,你的Robots類派生類的Map是因爲Map::getRobotsVector()也只是意味着你要調用getRobotsVector方法上的RescueBot::action功能運行在實例上它的工作原理的原因。

解決方法是通過引用將Map的實例傳遞給action函數。

這是你的行動功能會是什麼樣子,那麼:

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

由於OP可能每次只有1個活動地圖,爲什麼他不想讓'getRobotsVector'靜態?這似乎是一個完全正確的解決方案恕我直言。 –

+0

@PawełStawarz它類似於一個單身人士,這是一個可怕的事情[一些很好的理由](http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons) –

+0

我不要只有1個動作功能。我有3個通過多態。當我改變我的rescuebot :: action我在編譯器得到這個錯誤: << void RescueBot :: action(Map&)'的原型不匹配'RescueBot'中的任何類型| >> – DnkStyle