举一个c.++虚函数的例子
时间: 2024-05-07 12:17:56 浏览: 10
当一个基类中的函数被声明为虚函数时,它可以被任何派生类重新定义,这个过程被称为函数的覆盖。虚函数是实现多态性的一种机制,它可以使得不同类的对象调用同一个函数时表现出不同的行为。
以下是一个简单的 C++ 虚函数的例子:
```cpp
#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;
// 调用矩形的求面积函数 area
shape->area();
return 0;
}
```
在上面的例子中,`Shape` 类中的 `area()` 函数被声明为虚函数。`Rectangle` 类是 `Shape` 类的派生类,它覆盖了基类的 `area()` 函数。然后我们创建了一个 `Rectangle` 对象,并将其地址存储在 `Shape` 类型的指针变量中。调用 `shape->area();` 时,程序会根据指针所指向的实际对象类型来调用相应的函数。由于 `shape` 指向的是一个 `Rectangle` 对象,因此调用的是 `Rectangle` 类中覆盖了基类函数的 `area()` 函数。