Advertisement
RobertDeMilo

YB5.5 Решение проблемы с помощью виртуальных методов

Apr 14th, 2024
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. Базовый класс ничего не знает про методы классов потомков
  2.  
  3. #include <iostream>
  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 Voice()const{}
  19.  
  20. private:
  21.     const string type_;
  22. };
  23.  
  24. class Cat : public Animal
  25. {
  26. public:
  27.  
  28.     Cat():Animal("cat"){}
  29.  
  30.  
  31.     void Voice() const override
  32.     {
  33.         cout << "Meow! " << endl;
  34.     }
  35. };
  36.  
  37. class Dog : public Animal
  38. {
  39. public:
  40.  
  41.     Dog():Animal("dog"){}
  42.  
  43.     void Voice() const override
  44.     {
  45.         cout << "Whaf! " << endl;
  46.     }
  47. };
  48.  
  49. class Parrot:public Animal
  50. {
  51. public:
  52.  
  53.     Parrot(const string& name):Animal("parrot"),name_(name){}
  54.  
  55.     void Voice() const override
  56.     {
  57.         cout<<name_<<" is good!"<<endl;
  58.     }
  59.    
  60. private:
  61.     const string& name_;
  62. };
  63.  
  64. void MakeSound(const Animal& a)
  65. {
  66.     a.Voice();
  67. }
  68.  
  69. int main()
  70. {
  71.     Cat c;
  72.     Dog d;
  73.     Parrot p("Kesha");
  74.  
  75.     MakeSound(c);
  76.     MakeSound(d);
  77.     MakeSound(p);
  78.  
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement