/*动态多态
1:子类继承父类
2:子类重写父类虚函数
3:父类引用指向子类实现
*/
class Animal {
public:
virtual void speak() {//虚函数//虚函数指针 vfptr->虚函数表vftable
cout << "animal shout" << endl;
}
};
class Cat :public Animal{
public:
void speak() {//重写
cout << "喵喵" << endl;
}
};
class Dog :public Animal {
public:
void speak() {//重写
cout << "汪汪" << endl;
}
};
void doSpeak(Animal& animal) {//父类引用指向子类实现
animal.speak();
}
void test() {
Cat cat;
doSpeak(cat);
Dog dog;
doSpeak(dog);
}
int main() {
test();
}
/*结果:
喵喵
汪汪
*/