#include<iostream>
using namespace std;
#include<math.h>
const double pi=3.1415926;
class Shape
{
public:
virtual void Display()=0;
virtual double Area() const=0;
virtual double Volume() const=0;
void Disp();
virtual ~Shape(){};
};
class Sphere:public Shape //球体
{
public:
Sphere(double r=0.0)
{
radius=r;
}
void Display();
double Area() const;
double Volume() const;
virtual ~Sphere(){};
private:
double radius;
};
class Cuboid:public Shape //长方体
{
public:
Cuboid(double l=0.0,double w=0.0,double h=0.0)
{
length=l;
width=w;
heigth=h;
}
void Display();
double Area() const;
double Volume() const;
virtual ~Cuboid(){};
private:
double length;
double width;
double heigth;
};
class Cylinder:public Shape //圆柱体
{
public:
Cylinder(double r=0.0,double h=0.0)
{
radius=r;
heigth=h;
}
void Display();
double Area() const;
double Volume()const;
virtual ~Cylinder(){};
private:
double radius;
double heigth;
};
void Shape::Disp() //输出表面积和体积
{
cout<<"表面积="<<Area()<<endl;
cout<<"体积="<<Volume()<<endl;
}
void Sphere::Display()
{
cout<<"球半径="<<radius<<endl;
}
double Sphere::Area() const //球体表面积
{
double a;
a=4.0*pi*radius*radius;
return a;
}
double Sphere::Volume() const //球体体积
{
double a;
a=4.0/3.0*pi*pow(radius,3.0);
return a;
}
void Cuboid::Display()
{
cout<<"长方体长"<<length<<",宽"<<width<<",高"<<heigth<<endl;
}
double Cuboid::Area() const //长方体表面积
{
double a;
a=2.0*(length*width+width*heigth+heigth*length);
return a;
}
double Cuboid::Volume() const //长方体体积
{
double a;
a=length*width*heigth;
return a;
}
void Cylinder::Display()
{
cout<<"圆柱体半径"<<radius<<",高"<<heigth<<endl;
}
double Cylinder::Area() const //圆柱体表面积
{ double a;
a=2.0*pi*radius*(radius+heigth);
return a;
}
double Cylinder::Volume() const //圆柱体体积
{
double a;
a=pi*radius*radius*heigth;
return a;
}
#include "test.h"
int main()
{
int i;
Shape *ptrs[3];
ptrs[0]=new Sphere(10);
ptrs[1]=new Cuboid(12.5,5,2.5);
ptrs[2]=new Cylinder(10,10);
for(i=0;i<3;i++)
{
ptrs[i]->Display();
ptrs[i]->Disp();
}
system("pause");
return 0;
}
函数式编程
不负相思意