多态基本语法

#include <iostream>

class Animal
{
public:
   virtual void talk()
   {
      std::cout << "Animal talk" << std::endl;
   }
};

class Dog: public Animal
{
public:
   void talk()
   {
      std::cout << "Dog talk" << std::endl;
   }
};

class Cat: public Animal
{
public:
   void talk()
   {
      std::cout << "Cat talk" << std::endl;
   }
};

//运行阶段绑定 地址晚绑定
void talk(Animal &animal)
{
   animal.talk();
}

int main()
{
   Dog dog;
   talk(dog);

   Cat cat;
   talk(cat);

   return 0;
}
$ ./a.out       
Dog talk
Cat talk
posted @ 2022-07-06 19:05  thomas_blog  阅读(18)  评论(0编辑  收藏  举报