Advertisement
RobertDeMilo

YB5.6 Свойства виртуальных методов. Абстрактные классы

Apr 14th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Animal
  6. {
  7. public:
  8.  
  9.     Animal(const string& type):type_(type){}
  10.  
  11.     void Eat(const string& fruit)
  12.     {
  13.         cout<<type_<<" eats "<<fruit<<endl;
  14.     }
  15.  
  16.     //  virtual void Voice()const
  17.     //  {
  18.     //      cout<< type_<<" is silent"<<endl;
  19.     //  }
  20.  
  21.     virtual void Voice()const =0;
  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 Voice() 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 Voice() 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 Voice() 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.Voice();
  77. }
  78.  
  79. int main()
  80. {
  81.     Cat c;
  82.     Dog d;
  83.     Parrot p("Kesha");
  84.     Horse h;
  85.  
  86.     MakeSound(c);
  87.     MakeSound(d);
  88.     MakeSound(p);
  89.     MakeSound(h);
  90.  
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement