定义一个抽象类Shape,定义一个纯虚函数area()用以计算面积,从Shape派生出长方形、梯形、圆形派生类。程序中通过基类指针来调用派生类中的纯虚函数,计算不同形状的面积。
时间: 2024-03-26 11:36:02 浏览: 13
以下是实现要求的 C++ 代码示例:
```cpp
#include <iostream>
using namespace std;
// 抽象类 Shape
class Shape {
public:
// 纯虚函数 area()
virtual double area() = 0;
};
// 长方形类 Rectangle
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) {
width = w;
height = h;
}
// 实现纯虚函数 area()
double area() {
return width * height;
}
};
// 梯形类 Trapezoid
class Trapezoid : public Shape {
private:
double top;
double bottom;
double height;
public:
Trapezoid(double t, double b, double h) {
top = t;
bottom = b;
height = h;
}
// 实现纯虚函数 area()
double area() {
return (top + bottom) * height / 2;
}
};
// 圆形类 Circle
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
// 实现纯虚函数 area()
double area() {
return 3.14 * radius * radius;
}
};
// 主函数
int main() {
// 定义基类指针和派生类对象
Shape* shape;
Rectangle rect(3, 4);
Trapezoid trap(2, 4, 3);
Circle cir(2);
// 使用基类指针调用不同派生类的 area() 函数
shape = ▭
cout << "Rectangle area: " << shape->area() << endl;
shape = &trap;
cout << "Trapezoid area: " << shape->area() << endl;
shape = ○
cout << "Circle area: " << shape->area() << endl;
return 0;
}
```
运行结果:
```
Rectangle area: 12
Trapezoid area: 9
Circle area: 12.56
```
这个程序定义了抽象基类 `Shape`,并从中派生出了三个具体的形状类 `Rectangle`、`Trapezoid` 和 `Circle`。每个派生类都实现了基类的纯虚函数 `area()`,用于计算不同形状的面积。在主函数中,使用基类指针分别调用不同派生类的 `area()` 函数,输出不同形状的面积。