Advertisement
RobertDeMilo

YB5.8 Хранение объектов разных типов в контейнере с помощью shared ptr

Apr 14th, 2024
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4.  
  5. using namespace std;
  6.  
  7. class Animal
  8. {
  9. public:
  10.  
  11.     Animal(const string& type):type_(type){}
  12.  
  13.     void Eat(const string& fruit)
  14.     {
  15.         cout<<type_<<" eats "<<fruit<<endl;
  16.     }
  17.  
  18.     virtual void Sound()const
  19.     {
  20.         cout<< type_<<" is silent"<<endl;
  21.     }
  22.  
  23. private:
  24.     const string type_;
  25. };
  26.  
  27. class Cat : public Animal
  28. {
  29. public:
  30.  
  31.     Cat():Animal("cat"){}
  32.  
  33.  
  34.     void Sound() const override
  35.     {
  36.         cout << "Meow! " << endl;
  37.     }
  38. };
  39.  
  40. class Dog : public Animal
  41. {
  42. public:
  43.  
  44.     Dog():Animal("dog"){}
  45.  
  46.     void Sound() const override
  47.     {
  48.         cout << "Whaf! " << endl;
  49.     }
  50. };
  51.  
  52. class Parrot:public Animal
  53. {
  54. public:
  55.  
  56.     Parrot(const string& name):Animal("parrot"),name_(name){}
  57.  
  58.     void Sound() const override
  59.     {
  60.         cout<<name_<<" is good!"<<endl;
  61.     }
  62.  
  63. private:
  64.     const string name_;
  65. };
  66.  
  67. class Horse: public Animal
  68. {
  69. public:
  70.     Horse():Animal("horse"){}
  71.  
  72. };
  73.  
  74. void MakeSound(const Animal& a)
  75. {
  76.     a.Sound();
  77. }
  78.  
  79. int main()
  80. {
  81. //  shared_ptr<Animal> a;
  82. //  a = make_shared<Cat>();
  83. //  a->Sound();
  84. //  a->Eat("oranges");
  85.  
  86.     vector<shared_ptr<Animal>> animals =
  87.     {
  88.         make_shared<Cat>(),
  89.         make_shared<Dog>(),
  90.         make_shared<Parrot>("Kesha")
  91.     };
  92.  
  93.     for(auto a: animals)
  94.     {
  95.         MakeSound(*a);
  96.     }
  97.  
  98.     return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement