fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. enum COMPONENT_TYPE {
  7. ITEM,
  8. BAG,
  9. };
  10.  
  11. class Component {
  12. private:
  13. COMPONENT_TYPE type;
  14. string name;
  15. public:
  16. Component(COMPONENT_TYPE t, string n) {
  17. this->type = t;
  18. this->name = n;
  19. }
  20. string getType() {
  21. if (this->type == COMPONENT_TYPE::BAG) {
  22. return "BAG";
  23. }
  24. else {
  25. return "ITEM";
  26. }
  27. }
  28. string getName() {
  29. return this->name;
  30. }
  31. };
  32.  
  33. class Item : public Component {
  34. public:
  35. Item(string n) : Component(COMPONENT_TYPE::ITEM, n) {
  36. }
  37. };
  38.  
  39. class Bag : public Component {
  40. public:
  41. vector<Component>* contents = new vector<Component>();
  42. Bag(string n) : Component(COMPONENT_TYPE::BAG, n) {
  43. }
  44. };
  45.  
  46. int main() {
  47. Bag* outer = new Bag("big bag");
  48. Item* item1 = new Item("sword");
  49. Item* item2 = new Item("shield");
  50. Bag* inner = new Bag("small bag");
  51. outer->contents->push_back(*item1);
  52. outer->contents->push_back(*item2);
  53. outer->contents->push_back(*inner);
  54. Item* item3 = new Item("food");
  55. Item* item4 = new Item("potion");
  56. inner->contents->push_back(*item3);
  57. inner->contents->push_back(*item4);
  58.  
  59. std::cout << "Outer bag includes : " << std::endl;
  60. for (Component i : *outer->contents) {
  61. std::cout << i.getType() << " - " << i.getName() << std::endl;
  62. }
  63. std::cout << "Inner bag includes : " << std::endl;
  64. for (Component i : *inner->contents) {
  65. std::cout << i.getType() << " - " << i.getName() << std::endl;
  66. }
  67.  
  68. return 0;
  69. }
  70.  
Success #stdin #stdout 0s 4256KB
stdin
Standard input is empty
stdout
Outer bag includes : 
ITEM - sword
ITEM - shield
BAG - small bag
Inner bag includes : 
ITEM - food
ITEM - potion