要求如下:编写一个能计算不同形状的面积数组的小程序,定义抽象类Shape,由它派生出5个派生类:Circle(圆),Square(正方形),Rectangle(矩形),Trapezoid(梯形),Triangle(三角形),用虚函数area()分别计算几种图形的面积,并求他们的和,要求使用基类指针数组,使它的每个元素都指向一个派生类对象。根据上述要求完善下列代码 #include <iostream> using namespace std; #include<string> #include"time.h" #include"math.h" #define PI 3.1415926; //请在begin和end之间填入代码 /begin***/ /end/ int main() { double r,h,e1,e2,e3,eup,ebo,w; cin>>r; Circle c(r); cin>>w; Square sq(w); cin>>e1>>e2>>e3; Triangle tr(e1,e2,e3); cin>>w>>h; Rectangle re(w,h); cin>>eup>>ebo>>h; Trapezoid trap(eup,ebo,h); double sum=0; /begin/ /*end/ cout<<"area sum="<<sum; }
时间: 2024-04-27 14:21:13 浏览: 103
/begin***/
class Shape{
public:
virtual double area() = 0; //纯虚函数,用来计算面积
};
class Circle : public Shape{
private:
double radius;
public:
Circle(double r){
radius = r;
}
double area(){ //计算圆的面积
return PI * pow(radius,2);
}
};
class Square : public Shape{
private:
double width;
public:
Square(double w){
width = w;
}
double area(){ //计算正方形的面积
return pow(width,2);
}
};
class Rectangle : public Shape{
private:
double width;
double height;
public:
Rectangle(double w, double h){
width = w;
height = h;
}
double area(){ //计算矩形的面积
return width * height;
}
};
class Trapezoid : public Shape{
private:
double upperEdge;
double bottomEdge;
double height;
public:
Trapezoid(double u, double b, double h){
upperEdge = u;
bottomEdge = b;
height = h;
}
double area(){ //计算梯形的面积
return (upperEdge + bottomEdge) * height / 2;
}
};
class Triangle : public Shape{
private:
double edge1;
double edge2;
double edge3;
public:
Triangle(double e1, double e2, double e3){
edge1 = e1;
edge2 = e2;
edge3 = e3;
}
double area(){ //计算三角形的面积
double p = (edge1 + edge2 + edge3) / 2;
return sqrt(p * (p - edge1) * (p - edge2) * (p - edge3));
}
};
/*end*/
int main() {
double r,h,e1,e2,e3,eup,ebo,w;
cin>>r;
Circle c(r);
cin>>w;
Square sq(w);
cin>>e1>>e2>>e3;
Triangle tr(e1,e2,e3);
cin>>w>>h;
Rectangle re(w,h);
cin>>eup>>ebo>>h;
Trapezoid trap(eup,ebo,h);
double sum=0;
Shape* pShapes[5]; //定义基类指针数组
pShapes[0] = &c; //将派生类对象的地址赋值给基类指针数组元素
pShapes[1] = &sq;
pShapes[2] = &tr;
pShapes[3] = &re;
pShapes[4] = &trap;
for(int i=0; i<5; i++){
sum += pShapes[i]->area(); //调用虚函数计算面积
}
cout<<"area sum="<<sum;
return 0;
}
阅读全文