c++ 虚函数示例代码
时间: 2023-08-03 14:45:34 浏览: 56
以下是一个简单的 C++ 虚函数示例代码:
```cpp
#include <iostream>
using namespace std;
// 基类
class Shape {
protected:
double width, height;
public:
Shape(double w = 0, double h = 0) {
width = w;
height = h;
}
virtual double area() {
cout << "Parent class area :" << endl;
return 0;
}
};
// 派生类
class Rectangle : public Shape {
public:
Rectangle(double w = 0, double h = 0) : Shape(w, h) {}
double area() override {
cout << "Rectangle class area :" << endl;
return (width * height);
}
};
int main() {
Shape* shape;
Rectangle rect(5, 6);
shape = ▭
// 调用矩形的求面积函数
cout << shape->area() << endl;
return 0;
}
```
这个程序中,我们定义了一个基类 Shape 和一个派生类 Rectangle。在 Shape 中,我们定义了一个虚函数 area(),在 Rectangle 中重写了这个函数。在 main() 函数中,我们定义了一个指向 Shape 类型的指针,用一个 Rectangle 对象的地址初始化它。然后我们调用这个指针的 area() 函数,由于 area() 是虚函数,因此程序会调用 Rectangle 中的 area() 函数。