编写一个程序,定义抽象基类Shape,由它派生出5个派生类:Circle、Square、Rectangle、Trapezoid、Triangle。用虛函数分别计算几种图形面积,并求它们之和。
时间: 2023-07-10 18:32:10 浏览: 154
好的,这是一个 C++ 的程序:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
};
class Circle : public Shape {
double r;
public:
Circle(double radius) : r(radius) {}
virtual double area() const {
return 3.14159 * r * r;
}
};
class Square : public Shape {
double l;
public:
Square(double length) : l(length) {}
virtual double area() const {
return l * l;
}
};
class Rectangle : public Shape {
double l, w;
public:
Rectangle(double length, double width) : l(length), w(width) {}
virtual double area() const {
return l * w;
}
};
class Trapezoid : public Shape {
double h, b1, b2;
public:
Trapezoid(double height, double base1, double base2) : h(height), b1(base1), b2(base2) {}
virtual double area() const {
return (b1 + b2) * h / 2;
}
};
class Triangle : public Shape {
double h, w;
public:
Triangle(double height, double width) : h(height), w(width) {}
virtual double area() const {
return w * h / 2;
}
};
int main() {
Shape* shapes[5];
shapes[0] = new Circle(1.0);
shapes[1] = new Square(2.0);
shapes[2] = new Rectangle(3.0, 4.0);
shapes[3] = new Trapezoid(5.0, 6.0, 7.0);
shapes[4] = new Triangle(8.0, 9.0);
double sum = 0;
for (int i = 0; i < 5; i++) {
sum += shapes[i]->area();
}
cout << "The sum of areas is " << sum << endl;
return 0;
}
```
在这个程序中,我们定义了一个抽象基类 `Shape`,它有一个纯虚函数 `area()`,用于计算图形面积。然后我们派生出了五个具体的图形类,分别实现了它们的 `area()` 函数。在 `main()` 函数中,我们创建了五个不同的图形对象,并将它们的指针存入一个数组中。然后我们遍历这个数组,依次调用每个图形对象的 `area()` 函数,并将结果累加到 `sum` 变量中。最后输出 `sum` 的值,即为所有图形的面积之和。
阅读全文