Unit14-problem3-立体类族共有的抽象类

来源:互联网 发布:32位ubuntu系统下载 编辑:程序博客网 时间:2024/06/05 07:19
/*Univercity:烟台大学*@Class</A>计134~4*@Author:薛富磊*@Time:2014-5-27*@Function:设计一个抽象类CSolid,含有用于求表面积及体积的两个纯虚函数。            设计派生类CCube、CBall、CCylinder,分别表示正方体、球体及圆柱体。            在main()函数中,定义CSolid *p;(p是指向基类的指针,且这个基类是个抽象类)。            要求利用这个p指针,能够求出正方体、球体及圆柱体对象的表面积及体积。*@Args:*@Return:*/#include<iostream>using namespace std;//抽象立体图形基类class CSolid{    public:         virtual double SurfaceArea() const=0;         virtual double Volume() const=0;};//正方体类class CCube:public CSolid{    protected:              double length;    public:           CCube(double l=0):length(l){}           double SurfaceArea() const;           double Volume() const;};//求正方体面积double CCube::SurfaceArea() const{    return 6*length*length;}//求正方体体积double CCube::Volume() const{    return length*length*length;}//球体类class CBall:public CSolid{    protected:              double radius;    public:           CBall(double r=0):radius(r){}           double SurfaceArea() const;           double Volume() const;};//求球体表面积double CBall::SurfaceArea() const{    return 4*3.14*radius*radius;}//求球体体积double CBall::Volume() const{    return 3.14*radius*radius*radius*4/3;}//圆柱类class CCylinder:public CSolid{   protected:             double high;             double radius;   public:           CCylinder(double h=0,double r=0):high(h),radius(r){}           double SurfaceArea() const;           double Volume() const;};//求圆柱表面积double CCylinder::SurfaceArea() const{    return 2*3.14*radius*high+2*3.14*radius*radius;}//求圆柱体积double CCylinder::Volume() const{    return 3.14*radius*radius*high;}int main(){    CSolid *p;    double s,v;    CCube x(7);    cout<<"正方体边长为:7"<<endl;    p=&x;    s=p->SurfaceArea();    v=p->Volume();    cout<<"正方体表面积:"<<s<<" 体积:"<<v<<endl;    cout<<endl;    CBall y(2.5);    cout<<"球体的半径为:7"<<endl;    p=&y;    s=p->SurfaceArea();    v=p->Volume();    cout<<"球体表面积:"<<s<<" 体积:"<<v<<endl;    cout<<endl;    CCylinder z(7,2.5);    cout<<"圆柱的高和半径分别为:7,2.5"<<endl;    p=&z;    s=p->SurfaceArea();    v=p->Volume();    cout<<"圆柱体表面积:"<<s<<" 体积:"<<v<<endl;    cout<<endl;}

0 0
原创粉丝点击