简体   繁体   中英

How can an object of a vector access the vector elements

This is a program that simulates a simple resource gathering game The robots gather resources from the map and move around randomly each one doing some actions. My problem is that i want to access a vector from class map within the derivered class of robots "RescueBot" . The program is written in multiple files, header.h , header.cpp, main.cpp

I have a vector of objects type "Robots" and an example of my header.h file:

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
}

This is from the header.cpp file:

#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

   }
}

I Have tried making the Robots class derivered class of Map. After that when i run it the vector i access in RescueBot::action is empty, while the actual vector has objects in it. If i dont make it derivered it doesnt compile.

How can i access the vector from within the RescueBot::action() ??

The problem is that you have no Map instances.

The way you're calling it currently would only work if the getRobotsVector method were static , but you don't want that .

The reason it works when you make the Robots class a derived class of Map is because Map::getRobotsVector() would just mean you want to invoke the getRobotsVector method on the instance that the RescueBot::action function is operating on.

The solution is to pass an instance of a Map to your action functions by reference.

This is what your action function would look like then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM