声明一个Animal类,派生出Dog类和Cat类,三个类中都定义Speak函数,其中基类中的Speak函数为虚函数。写出主函数并实现运行时的多态。
时间: 2024-03-08 07:51:29 浏览: 40
以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Animal {
public:
virtual void Speak() {
cout << "This is an animal." << endl;
}
};
class Dog : public Animal {
public:
void Speak() {
cout << "This is a dog." << endl;
}
};
class Cat : public Animal {
public:
void Speak() {
cout << "This is a cat." << endl;
}
};
int main() {
Animal *animal;
Dog dog;
Cat cat;
animal = &dog;
animal->Speak();
animal = &cat;
animal->Speak();
return 0;
}
```
在这段代码中,我们首先声明了一个基类 `Animal`,并将其 `Speak` 函数声明为虚函数。接着,我们派生出了 `Dog` 类和 `Cat` 类,并在这两个类中都定义了 `Speak` 函数。由于 `Animal` 类中的 `Speak` 函数为虚函数,因此在派生类中重写 `Speak` 函数时也需要在函数签名前加上 `virtual` 关键字。
在主函数中,我们首先定义了一个 `Animal` 类型的指针变量 `animal`,然后将其指向 `Dog` 类的对象 `dog`,调用 `Speak` 函数时会发现输出的是 `Dog` 类的内容。接着,我们将 `animal` 指针变量指向 `Cat` 类的对象 `cat`,调用 `Speak` 函数时会发现输出的是 `Cat` 类的内容。这就是运行时的多态性,通过基类指针变量指向派生类对象,调用虚函数时会根据实际的对象类型来选择调用哪个类中的函数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)