定义一个shape抽象类,在此基础上派生出rectangle和circle类,二者均有计算面积周长的函数。

2024-12-27 19:26:34
推荐回答(2个)
回答1:

不要提出这种问题,代码还是自己动手写的好,写的过程中遇到麻烦,再拿出来问的话,我想会有更多人乐意帮你解答的

回答2:

#include
using namespace std;
class Shape
{
public:
virtual double area() const =0;//定义纯虚函数
};

class Circle:public Shape
{
public:
Circle(double r):radius(r) {}
double area() const;
private:
double radius;
};
double Circle::area()const
{
return(radius*radius*3.14);
}

class Rectangle:public Shape
{
public:
Rectangle(double w,double h):width(w),height(h){}
double area( ) const;

private:
double width;
double height;
};

double Rectangle::area( )const
{
return width*height;
}

class Triangle:public Shape
{
public:
Triangle(double x,double y):wid(x),hei(y) {}
double area( )const;
private:
double wid;
double hei;
};

double Triangle::area( )const
{
return 0.5*wid*hei;
}

int main()
{
Circle c1(12.6),c2(4.9);
Rectangle r1(4.5,8.4),r2(5.0,2.5);
Triangle t1(4.5,8.4),t2(3.4,2.8);
Shape *pt[6]= {&c1,&c2,&r1,&r2,&t1,&t2};
double areas=0.0; //areas为总面积
for(int i=0;i<6;i++)
{
areas=areas+pt[i]->area();
}
cout<<"totol of all areas="<return 0;
}