如何使用虚函数实现多态性?
时间: 2024-05-03 10:17:32 浏览: 15
使用虚函数实现多态性需要满足以下条件:
1. 父类中声明虚函数。
2. 子类中重写虚函数。
3. 通过父类指针或引用调用虚函数。
具体实现方式如下:
1. 在父类中声明虚函数。
```c++
class Animal {
public:
virtual void makeSound() {
cout << "Animal makes sound." << endl;
}
};
```
2. 在子类中重写虚函数。
```c++
class Cat : public Animal {
public:
void makeSound() {
cout << "Meow!" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() {
cout << "Woof!" << endl;
}
};
```
3. 通过父类指针或引用调用虚函数。
```c++
int main() {
Animal* animal1 = new Cat();
animal1->makeSound(); // 输出 "Meow!"
Animal* animal2 = new Dog();
animal2->makeSound(); // 输出 "Woof!"
delete animal1;
delete animal2;
return 0;
}
```
在上述代码中,父类 Animal 声明了虚函数 makeSound(),子类 Cat 和 Dog 分别重写了这个函数。在主函数中,通过父类指针 animal1 和 animal2 分别指向子类 Cat 和 Dog 的对象,并调用它们的 makeSound() 函数。由于 makeSound() 是虚函数,所以会根据对象的实际类型进行动态绑定,最终输出正确的结果。这就是多态性的实现方式之一。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)