写一个程序定义抽象类shape由它的派生类圆形正方形,然后用虚函数,计算图形面积然后求和,要用基类指针数组,使它的每一个元素指向一个派生类对象
时间: 2024-04-14 15:26:09 浏览: 21
以下是一个示例程序,演示了如何定义抽象类 Shape,以及派生类 Circle 和 Square。程序使用虚函数计算图形的面积,并通过基类指针数组将每个元素指向派生类对象,并计算它们的面积总和。
```cpp
#include<iostream>
using namespace std;
class Shape{
public:
virtual float Area() const = 0; // 纯虚函数
};
class Circle: public Shape{
private:
float radius;
public:
Circle(float r){
radius = r;
}
float Area() const {
return 3.14 * radius * radius;
}
};
class Square: public Shape{
private:
float side;
public:
Square(float s){
side = s;
}
float Area() const {
return side * side;
}
};
int main(){
const int numShapes = 4;
Shape* shapes[numShapes];
shapes[0] = new Circle(5.0);
shapes[1] = new Square(4.0);
shapes[2] = new Circle(3.0);
shapes[3] = new Square(2.0);
float totalArea = 0.0;
for(int i = 0; i < numShapes; i++){
totalArea += shapes[i]->Area();
}
cout << "Total area: " << totalArea << endl;
// 释放内存
for(int i = 0; i < numShapes; i++){
delete shapes[i];
}
return 0;
}
```
在这个程序中,我们定义了一个抽象基类 Shape,其中有一个纯虚函数 Area(),表示计算图形的面积。然后,我们派生了两个类 Circle 和 Square,并分别实现了它们自己的 Area() 函数。
在主函数中,我们创建了一个大小为 4 的指针数组 `shapes`,并将数组中的每个元素指向一个派生类对象。然后,我们遍历该数组,使用多态性调用每个对象的 Area() 函数,并计算总面积。
最后,我们释放了动态分配的内存,以避免内存泄漏。