38 lines
576 B
C++
38 lines
576 B
C++
|
// 多态本质:
|
||
|
// 父类引用或指针指向子类对象,通过父类指针或引用来(操作子类对象)调用子类中重写的成员函数
|
||
|
#include <iostream>
|
||
|
#include <cstring>
|
||
|
#include <cstdlib>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
class Animal
|
||
|
{
|
||
|
public:
|
||
|
virtual void speak()
|
||
|
{
|
||
|
cout << "动物在唱歌..." << endl;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
class Dog : public Animal
|
||
|
{
|
||
|
public:
|
||
|
void speak()
|
||
|
{
|
||
|
cout << "狗在唱歌..." << endl;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
void DoBusiness(Animal &animal)
|
||
|
{
|
||
|
animal.speak();
|
||
|
}
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
Dog dog;
|
||
|
DoBusiness(dog);
|
||
|
return 0;
|
||
|
}
|