编写一个程序定义抽象类有他派生五个派生类 圆 正方形 矩形 梯形 三角形用函数分别求面积 总面积 要求用基类指针数组

#include<iostream>
using namespace std;
class Shape
{public:
virtual double area()const=0;
};
class Circle:public Shape
{public:
Circle(double r):radius(r){}
virtual double area() const{return 3.14159*radius*radius;};
protected:
 double radius;
};
class Square:public Shape
{public:
Square(double s):side(s){}
virtual double area()const{return side*side;}
protected:
 double side;
};
class Rectangle:public Shape
{public:
    Rectangle(double w, double h):width(w),height(h){}
 virtual double area()const{return width*height;}
protected:
 double width,height;
};
class Trapezoid:public Shape

public:
 Trapezoid(double t,double b,double h):top(t),bottom(t),height(h){}
 virtual double area()const{return 0.5*(top*bottom)*height;}
protected:
 double top,bottom,height;
};
class Triangle:public Shape
{
public:
 Triangle(double w,double h):width(w),height(h){}
 virtual double area()const{return 0.5*width*height;}
protected:
 double width,height;
};
int main()
{ Circle circle(12.6);
  Square square(3.5);
  Rectangle rectangle(4.5,8.4);
  Trapezoid trapezoid(2.0,4.5,3.2);
  Triangle triangle(4.5,8.4);
  Shape *pt[5]={&circle,&square,&rectangle,&trapezoid,&triangle};]
  double areas=0.0;
  for(int i=0;i<5;i++)
  {areas=areas+pt[i]->area();}
  cout<<"total of all area="<<areas<<endl;
  return 0;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个示例程序,演示了如何定义抽象类 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() 函数,并计算总面积。 最后,我们释放了动态分配的内存,以避免内存泄漏。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值