写一个程序,定义抽象基类Shape,由它派生出3个派生类:Circle(圆形),Square(正方形),Rectangle(矩形)。用虚函数分别计算几种图形面积,并求它们的和。要求用基类指针数组,使它的每一个元素指向一个派生类对象。
时间: 2024-05-05 16:18:26 浏览: 179
好的,对于您的问题,我非常乐意为您解答。
以下是用C++实现的程序,满足您的要求:
```c++
#include <iostream>
using namespace std;
class Shape{
public:
virtual double getArea() = 0;
};
class Circle : public Shape{
public:
Circle(double r) : radius(r){ }
double getArea() {
return 3.14 * radius * radius;
}
private:
double radius;
};
class Square : public Shape{
public:
Square(double l) : length(l){ }
double getArea() {
return length * length;
}
private:
double length;
};
class Rectangle : public Shape{
public:
Rectangle(double l, double w) : length(l), width(w){ }
double getArea() {
return length * width;
}
private:
double length;
double width;
};
int main(){
Shape* shapes[3];
shapes[0] = new Circle(5);
shapes[1] = new Square(4);
shapes[2] = new Rectangle(3, 4);
double sum = 0;
for(int i = 0; i < 3; i++){
sum += shapes[i]->getArea();
}
cout << "The sum of the areas is: " << sum << endl;
delete shapes[0];
delete shapes[1];
delete shapes[2];
return 0;
}
```
我希望这个程序对您有所帮助。如果您有任何其他问题或疑问,请随时向我提问。
阅读全文