编写一个程序计算“正方形、圆形、三角形”三种图形的面积,要求: (1)抽象出一个基类Shape; (2)在其中说明一个纯虚函数用来求边长; (3)利用派生类定义“正方形、圆形、三角形”,并求出这三种图形的面积。 (4)编写主函数测试以上代码,要求以多态来实现。
时间: 2023-09-13 07:05:18 浏览: 134
好的,我可以帮你解决这个问题。
首先,我们需要定义一个基类Shape并声明一个纯虚函数用来求边长:
```cpp
class Shape {
public:
virtual double getEdge() const = 0;
};
```
接下来,我们可以定义三个派生类Square、Circle和Triangle,并实现它们的面积计算函数:
```cpp
class Square : public Shape {
public:
Square(double edge) : edge_(edge) {}
double getEdge() const override {
return edge_;
}
double getArea() const {
return edge_ * edge_;
}
private:
double edge_;
};
class Circle : public Shape {
public:
Circle(double radius) : radius_(radius) {}
double getEdge() const override {
return 2 * radius_;
}
double getArea() const {
return 3.1415926 * radius_ * radius_;
}
private:
double radius_;
};
class Triangle : public Shape {
public:
Triangle(double edge1, double edge2, double edge3) : edge1_(edge1), edge2_(edge2), edge3_(edge3) {}
double getEdge() const override {
return edge1_ + edge2_ + edge3_;
}
double getArea() const {
double p = (edge1_ + edge2_ + edge3_) / 2.0;
return sqrt(p * (p - edge1_) * (p - edge2_) * (p - edge3_));
}
private:
double edge1_;
double edge2_;
double edge3_;
};
```
最后,我们可以编写测试代码,使用多态的方式计算这三种图形的面积:
```cpp
int main() {
Shape* shapes[3];
shapes[0] = new Square(2.0);
shapes[1] = new Circle(1.0);
shapes[2] = new Triangle(3.0, 4.0, 5.0);
for (int i = 0; i < 3; i++) {
cout << "Shape " << i << " edge length: " << shapes[i]->getEdge() << endl;
cout << "Shape " << i << " area: " << shapes[i]->getArea() << endl;
}
for (int i = 0; i < 3; i++) {
delete shapes[i];
}
return 0;
}
```
输出结果为:
```
Shape 0 edge length: 2
Shape 0 area: 4
Shape 1 edge length: 2
Shape 1 area: 3.14159
Shape 2 edge length: 12
Shape 2 area: 6
```
这样就完成了题目要求的程序编写。
阅读全文