fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class Run;
  6.  
  7.  
  8. class Robot{
  9. friend class Run; // allows the Run class to access all the private data as if it were its own
  10. private:
  11. int x;
  12. public:
  13. Robot() {};
  14. void setX(int newX) { x= newX; }
  15. int getX() { return x; }
  16. void movingRobot() { x+=1; }
  17.  
  18. };
  19.  
  20. class Run{
  21. private:
  22. vector<Robot*> robots;
  23. public:
  24. Run(){};
  25. vector<Robot*> *getRobots() { return &robots; }
  26. void createRobot() { robots.push_back(new Robot()); robots.back()->x =1; }
  27. void movAll() { for (int i=0;i<robots.size();i++){ robots[i]->movingRobot();} }
  28. int getX(int robotPosition){ return robots[robotPosition]->x; } //uses the friend status to read directly from Robot class instances x
  29. void setX(int rpos, int xval){ robots[rpos]->setX(xval); }
  30. };
  31.  
  32.  
  33. int main()
  34. {
  35. Run *Sim = new Run();
  36. for (int i =0; i< 10; i++)
  37. {
  38. Sim->createRobot();
  39. Sim->setX(i,i); // uses the Run setX
  40. std::cout << "Robot " << i << "(starting position): " << Sim->getRobots()->at(i)->getX() << std::endl;
  41. }
  42. Sim->movAll();
  43. // lets move Johnny 5 to 55 as well...
  44. (Sim->getRobots()->at(4))->setX(55); // uses the robot setx
  45. for (int i=0; i< 10; i++)
  46. {
  47. std::cout << "Robot " << i << "(final position): " << Sim->getRobots()->at(i)->getX()<< std::endl;
  48. }
  49.  
  50.  
  51. return 0;
  52. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Robot 0(starting position): 0
Robot 1(starting position): 1
Robot 2(starting position): 2
Robot 3(starting position): 3
Robot 4(starting position): 4
Robot 5(starting position): 5
Robot 6(starting position): 6
Robot 7(starting position): 7
Robot 8(starting position): 8
Robot 9(starting position): 9
Robot 0(final position): 1
Robot 1(final position): 2
Robot 2(final position): 3
Robot 3(final position): 4
Robot 4(final position): 55
Robot 5(final position): 6
Robot 6(final position): 7
Robot 7(final position): 8
Robot 8(final position): 9
Robot 9(final position): 10