shushus

Спринт 11. Динамическое приведение типа.

Apr 6th, 2023
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. -----------------------------------------------------------------------
  2. animals.cpp
  3. -----------------------------------------------------------------------
  4. #include <iostream>
  5. #include <string>
  6. #include <string_view>
  7. #include <vector>
  8.  
  9. using namespace std;
  10.  
  11. class Speakable {
  12. public:
  13.     virtual ~Speakable() = default;
  14.     virtual void Speak(ostream& out) const = 0;
  15. };
  16.  
  17. class Drawable {
  18. public:
  19.     virtual ~Drawable() = default;
  20.     virtual void Draw(ostream& out) const = 0;
  21. };
  22.  
  23. class Animal {
  24. public:
  25.     virtual ~Animal() = default;
  26.     void Eat(string_view food) {
  27.         cout << GetType() << " is eating "sv << food << endl;
  28.         ++energy_;
  29.     }
  30.     virtual string GetType() const = 0;
  31.  
  32. private:
  33.     int energy_ = 100;
  34. };
  35.  
  36. class Fish : public Animal, public Drawable {
  37. public:
  38.     string GetType() const override {
  39.         return "fish"s;
  40.     }
  41.     void Draw(ostream& out) const override {
  42.         out << "><(((*>"sv << endl;
  43.     }
  44. };
  45.  
  46. class Cat : public Animal, public Speakable, public Drawable {
  47. public:
  48.     void Speak(ostream& out) const override {
  49.         out << "Meow-meow"sv << endl;
  50.     }
  51.     void Draw(ostream& out) const override {
  52.         out << "(^w^)"sv << endl;
  53.     }
  54.     string GetType() const override {
  55.         return "cat"s;
  56.     }
  57. };
  58.  
  59. void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
  60.     for(auto animal_ : animals) {        
  61.         if(const Drawable* animal = dynamic_cast<const Drawable*>(animal_)){
  62.             animal->Draw(out);
  63.         }
  64.     }
  65. }
  66.  
  67. void TalkToAnimals(const std::vector<const Animal*> animals, ostream& out) {
  68.     for(auto animal_ : animals) {        
  69.         if(const Speakable* animal = dynamic_cast<const Speakable*>(animal_)){
  70.             animal->Speak(out);
  71.         }
  72.     }
  73. }
  74.  
  75. void PlayWithAnimals(const std::vector<const Animal*> animals, ostream& out) {
  76.     TalkToAnimals(animals, out);
  77.     DrawAnimals(animals, out);
  78. }
  79.  
  80. int main() {
  81.     Cat cat;
  82.     Fish fish;
  83.     vector<const Animal*> animals{&cat, &fish};
  84.     PlayWithAnimals(animals, cerr);
  85. }
Advertisement
Add Comment
Please, Sign In to add comment