C++中的虚函数是什么你可以用代码的形式解释吗
时间: 2024-03-16 09:46:59 浏览: 24
C++中的虚函数是为了支持运行时多态性而设计的。它允许子类重写父类的函数并在运行时动态绑定到子类的实现。
以下是一个简单的例子:
```c++
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
int main() {
Shape *shape;
Rectangle rec(10,7);
shape = &rec;
shape->area();
return 0;
}
```
在这个例子中,Shape类声明了一个虚函数area(),并用关键字virtual修饰。Rectangle类继承自Shape类并重写了area()函数。在主函数中,我们创建了一个Rectangle对象并将其指针赋给一个Shape类型的指针。然后我们调用该指针的area()函数,程序将根据实际指向的对象类型动态绑定到正确的函数实现。
输出结果如下:
```
Rectangle class area :
```
可以看到,程序正确地调用了Rectangle类中重写的area()函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)