vc++ 应用纯虚函数的使用,定义几个派生类如三角形,矩形,圆形等,求出所有形状的总面积.
来源:学生作业帮助网 编辑:作业帮 时间:2024/05/10 06:54:07
vc++ 应用纯虚函数的使用,定义几个派生类如三角形,矩形,圆形等,求出所有形状的总面积.
vc++ 应用纯虚函数的使用,定义几个派生类如三角形,矩形,圆形等,求出所有形状的总面积.
vc++ 应用纯虚函数的使用,定义几个派生类如三角形,矩形,圆形等,求出所有形状的总面积.
/*Shape是一个几何图形的基类,它至少有求自身周长函数Circumference()和
求自身面积函数Area().从Shape类派生出Circle类、Ellipse类、Triangle类和
Rectangle类,分别继承基类Shape的Circumference()和Area(),并增加新的成员.
编写主函数,定义各派生类对象,要求用一个函数实现求多派生类对象的周长之和、面积之和.*/
#include
#include
#define PI 3.1415926
class CShape
{
public:
\x05virtual float Circumference()=0;
\x05virtual float Area()=0;
};
class CCircle:public CShape
{
public:
\x05CCircle(float r1)
\x05{
\x05\x05r=r1;
\x05}
\x05 float Circumference()
\x05 {
return (float)PI*r*2;
\x05 }
\x05 float Area()
\x05 {
\x05\x05 return (float)PI*r*r;
\x05 }
private:
\x05float r;
};
//L = pi(1.5(a+b)-sqrt(ab)),其中a,b分别为椭圆长轴和短轴.
class CEllipse:public CShape
{
public:
\x05CEllipse(float a1,float b1)
\x05{
\x05\x05a=a1;
\x05\x05b=b1;
\x05}
\x05float Circumference()
\x05{
\x05\x05float temp1=(float)(1.5)*(a+b);
\x05\x05float temp2=(float)sqrt(a*b);
return (float)PI*(temp1-temp2);
\x05}
\x05float Area()
\x05{
\x05\x05return (float)PI*a*b;
\x05}
private:
\x05float a;
\x05float b;
};
//Triangle面积公式
//s=根号下:p(p-a)(p-b)(p-c) 其中p=1/2(a+b+c) 这个公式叫海伦公式
class CTriangle:public CShape
{
public:
\x05CTriangle(float a1,float b1,float c1)
\x05{
\x05\x05a=a1;
\x05\x05b=b1;
\x05\x05c=c1;
\x05}
\x05\x05float Circumference()
\x05\x05{
\x05\x05\x05return (a+b+c);
\x05\x05}
\x05\x05float Area()
\x05\x05{
\x05\x05\x05float p=(a+b+c)/2;
\x05\x05\x05return (float)sqrt(p*(p-a)*(p-b)*(p-c));
\x05\x05}
private:
\x05float a;
\x05float b;
\x05float c;
};
class CRectangle:public CShape
{
public:
\x05CRectangle(float a1,float b1)
\x05{
\x05\x05a=a1;
\x05\x05b=b1;
\x05}
\x05float Circumference()
\x05{
\x05\x05return 2*(a+b);
\x05}
\x05float Area()
\x05{
\x05\x05return (float)a*b;
\x05}
private:
\x05float a;
\x05float b;
};
void main()
{
\x05void sum(CShape *p[],int n,float &zc,float &mj);
\x05CShape *p[4];
\x05CCircle q(1.0);//圆
CEllipse w(2.0,1.0);//椭圆
\x05CTriangle e(3.0,4.0,5.0);//三角形
\x05CRectangle r(1.0,2.0);//长方形
\x05p[0]=&q;
\x05p[1]=&w;
\x05p[2]=&e;
p[3]=&r;
\x05float zc=0,mj=0;
\x05sum(p,4,zc,mj);
\x05cout