父类的引用或者指针,指向子类对象
#include <iostream>
using namespace std;
class Animal{
public:
//动态连遍,在父类声明函数上,变成虚函数,发生了多态
virtual void speak()
{
cout<<"动物在说话"<<endl;
}
};
class Cat :public Animal
{
public:
void speak()
{
cout<<"小猫在说话"<<endl;
}
};
//静态连遍,编译阶段就确定好了地址,没有加virtual关键字
void dospeak(Animal &animal)
{
animal.speak();
}
void test()
{
Cat cat;
dospeak(cat);
}
int main()
{
test();
return 0;
}
原文:https://www.cnblogs.com/lodger47/p/14699381.html