请写出一个继承并实现多态性的代码示例
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void speak()
{
cout << "动物在说话" << 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 test01()
{
Cat cat;
Dospeak(cat);
Dog dog;
Dospeak(dog);
}
int main()
{
test01();
return 0;
}