请写一个C++示例,教我如何使用虚函数
时间: 2024-03-02 09:51:27 浏览: 18
好的,以下是一个简单的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()`,并且有一个子类 `Rectangle`,它重写了 `Shape` 类中的虚函数 `area()`。
在 `main()` 函数中,我们声明了一个 `Shape` 类型的指针 `shape`,并将它指向 `Rectangle` 类的对象 `rec`。然后,我们调用 `shape->area()` 函数,由于 `area()` 是虚函数,因此程序会根据 `rec` 对象的实际类型(即 `Rectangle`)来调用相应的函数。
因此,程序会输出:
```
Rectangle class area :
```
这个示例演示了虚函数的基本用法,它允许使用基类指针来调用派生类中的函数,从而实现多态性。