十三周任务四:设计一个抽象类CSolid,含有两个求表面积及体积的纯虚函数

/* (程序头部注释开始)
* 程序的版权和版本声明部分
* 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

请按任意键继续. . .

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值