一.多态的概念
二.静态多态
#include <iostream>
using namespace std;
class Animal//动物类
{
public:
void speak()
{
cout << "动物在说话" << endl;
}
};
class Cat :public Animal//猫类
{
public:
void speak()
{
cout << "小猫在说话" << endl;
}
};
void dospeak(Animal& animal)
{
animal.speak();//动物类才能调用
}
void test01()
{
Cat cat;//定义一个猫类
dospeak(cat);
}
int main()
{
test01();//动物在说话
return 0;
}
三.动态多态
改进:
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void speak()//虚函数:函数地址运行时才进行绑定
{
cout << "动物在说话" << endl;
}
};
class Cat :public Animal
{
void speak()
{
cout << "小猫在说话" << endl;
}
};
void dospeak(Animal& animal)
{
animal.speak();
}
void test01()
{
Cat cat;
dospeak(cat);
}
int main()
{
test01();//小猫在说话
return 0;
}