Advertisement
Guest User

Untitled

a guest
May 29th, 2015
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4.  
  5. using namespace std;
  6.  
  7. class GameObject
  8. {
  9. public:
  10. virtual void onContact(GameObject* otherObject)
  11. {
  12. cout << "object met object" << endl;
  13. }
  14. };
  15.  
  16. class Crate;
  17. class Wall;
  18. class Hero;
  19.  
  20. class Crate: public GameObject
  21. {
  22. public:
  23. virtual void onContact(Wall* w)
  24. {
  25. cout << "crate met wall" << endl;
  26. }
  27. virtual void onContact(Hero* h)
  28. {
  29. cout << "crate met hero" << endl;
  30. }
  31. };
  32.  
  33. class Wall: public GameObject
  34. {
  35. public:
  36. virtual void onContact(Crate* c)
  37. {
  38. cout << "wall met crate" << endl;
  39. }
  40. virtual void onContact(Hero* h)
  41. {
  42. cout << "wall met hero" << endl;
  43. }
  44. };
  45.  
  46.  
  47. class Hero: public GameObject
  48. {
  49. public:
  50. virtual void onContact(Crate* crate)
  51. {
  52. cout << "hero met crate" << endl;
  53. }
  54. virtual void onContact(Wall* w)
  55. {
  56. cout << "hero met wall" << endl;
  57. }
  58. };
  59.  
  60. int main()
  61. {
  62. //Works
  63. auto hero = unique_ptr<Hero>(new Hero());
  64. auto crate = unique_ptr<Crate>(new Crate());
  65. auto wall = unique_ptr<Wall>(new Wall());
  66.  
  67. hero->onContact(crate.get()); // "hero met crate"
  68. hero->onContact(wall.get()); // "hero met wall"
  69. crate->onContact(wall.get()); // "crate met wall"
  70. wall->onContact(crate.get()); // "wall met crate"
  71.  
  72. cout << endl;
  73.  
  74. //Problem: in the program the game objects are stored in a vector (homogeneous container)
  75. vector<unique_ptr<GameObject>> gameObjects;
  76. gameObjects.push_back(move(hero));
  77. gameObjects.push_back(move(crate));
  78. gameObjects.push_back(move(wall));
  79.  
  80. /*
  81. "object met object".
  82. Should be "hero met crate".
  83. That's because all objects in vector are GameObject.
  84. */
  85. gameObjects[0]->onContact(gameObjects[1].get());
  86.  
  87. /* "object met object", should be "wall met crate" */
  88. gameObjects[2]->onContact(gameObjects[1].get());
  89.  
  90. return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement