c++利用多态求各种图形面积
时间: 2024-02-03 12:38:20 浏览: 82
可以定义一个抽象基类 Shape,然后派生出各种具体的图形类,如 Circle、Rectangle、Triangle 等。在 Shape 类中定义一个纯虚函数 area(),每个具体的图形类都需要实现这个函数以计算自己的面积。然后使用指向 Shape 类的指针数组,遍历每个图形并调用其 area() 函数,最后累加得到所有图形的面积之和。
示例代码如下:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
public:
virtual double area() = 0; // 纯虚函数,计算面积
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
virtual double area() {
return M_PI * radius * radius;
}
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
virtual double area() {
return width * height;
}
};
class Triangle : public Shape {
private:
double a, b, c;
public:
Triangle(double side1, double side2, double side3) : a(side1), b(side2), c(side3) {}
virtual double area() {
double p = (a + b + c) / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
};
int main() {
Shape *shapes[] = { new Circle(5), new Rectangle(3, 4), new Triangle(3, 4, 5) };
double totalArea = 0;
for (int i = 0; i < 3; i++) {
totalArea += shapes[i]->area();
}
cout << "Total area: " << totalArea << endl;
return 0;
}
```
阅读全文