/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:
* 作 者: 田庆
* 完成日期: 2012 年 5 月 15 日
* 版 本 号:
* 对任务及求解方法的描述部分
* 输入描述: 设计个派生类CCube、CBall、CCylinder,分别表示正方体、球体及圆柱体。在main()函数中,定义基类的指针p(CSolid *p;),利用p指针,输出正方体、球体及圆柱体对象的表面积及体积。
* 问题描述:
* 程序输出:
* 程序头部的注释结束
*/
#include<iostream>
using namespace std;
class CSolid
{
public:
virtual float area() const=0;//表面积函数
virtual float volume() const=0;//体积函数
};
//定义正方体类,以CSolid为抽象基类
class CCube:public CSolid
{
public:
CCube(float length,float width,float heigth)
{
this->length = length;
this->width = width;
this->heigth = heigth;
}
virtual float area() const;
virtual float volume() const;
protected:
float length;
float width;
float heigth;
};
float CCube::area() const
{
return(length*width+length*heigth+width*heigth)*2;
}
float CCube::volume() const
{
return(length*heigth*width);
}
//定义球体,以CSolid为抽象基类
class CBall:public CSolid
{
public:
CBall(float radius)
{
this->radius = radius;
}
virtual float area() const;
virtual float volume() const;
protected:
float radius;
};
float CBall::area() const
{
return(4*3.14*radius*radius);
}
float CBall::volume() const
{
return(4/3*3.14*radius*radius*radius);
}
//定义圆柱体类,以CSolid为抽象基类
class CCylinder:public CSolid
{
public:
CCylinder(float radius,float heigth)
{
this->radius = radius;
this->heigth = heigth;
}
virtual float area() const;
virtual float volume() const;
protected:
float radius;
float heigth;
};
float CCylinder::area() const
{
return(2*3.14*radius*radius+2*3.14*radius*heigth);
}
float CCylinder::volume() const
{
return(3.14*radius*radius*heigth);
}
int main()
{
CSolid *p;
double s,v;
CCube x(30,23,3);
cout<<"矩形的长,宽,高分别为30,23,3"<<endl;
p=&x;
s=p->area( );
v=p->volume( );
cout<<"表面积:"<<s<<endl;
cout<<"体积:"<<v<<endl;
cout<<endl;
CBall y(5.4);
cout<<"球体半径为5.4"<<endl;
p=&y;
s=p->area( );
v=p->volume( );
cout<<"表面积:"<<s<<endl;
cout<<"体积:"<<v<<endl;
cout<<endl;
CCylinder z(10.2,21.6);
cout<<"圆柱体底面半径、高分别为10.2, 21.6"<<endl;
p=&z;
s=p->area( );
v=p->volume( );
cout<<"表面积:"<<s<<endl;
cout<<"体积:"<<v<<endl;
cout<<endl;
system("pause");
return 0;
}
运行结果:
矩形的长,宽,高分别为30,23,3
表面积:1698
体积:2070
球体半径为5.4
表面积:366.25
体积:494.437
圆柱体底面半径、高分别为10.2, 21.6
表面积:2036.98
体积:7056.41
请按任意键继续. . .