Advertisement
kutuzzzov

Урок 11 динамическое приведение типов

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