多态基本语法
#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