【任务4】设计一个抽象类CSolid,含有两个求表面积及体积的纯虚函数。设计个派生类CCube、CBall、CCylinder,分别表示正方体、球体及圆柱体。在main()函数中,定义基类的指针p(CSolid *p;),利用p指针,输出正方体、球体及圆柱体对象的表面积及体积。
/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:
* 作 者: 姜雅明
* 完成日期: 2012 年 05 月 20 日
* 版 本 号:
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:
* 程序头部的注释结束
*/
#include <iostream>
using namespace std;
const double pi = 3.1415926;
class CSolid
{
public:
virtual double area() =0{};
virtual double volume() =0{};
};
class CCube:public CSolid
{
private:
double length;
public:
CCube (double length);
virtual double area ();
virtual double volume();
};
CCube::CCube(double length)
{
this->length = length;
}
double CCube::area()
{
return length * length * 6;
}
double CCube::volume()
{
return length * length * length;
}
class CBall:public CSolid
{
private:
double radius;
public:
CBall (double r);
virtual double area ();
virtual double volume();
};
CBall::CBall(double radius)
{
this->radius = radius;
}
double CBall::area()
{
return 4 * pi * radius * radius;
}
double CBall::volume()
{
return 4 / 3 * pi * radius * radius * radius;
}
class CCylinder:public CSolid
{
private:
double radius;
double height;
public:
CCylinder (double radius, double height);
virtual double area ();
virtual double volume();
};
CCylinder::CCylinder(double radius, double height)
{
this->radius = radius;
this->height = height;
}
double CCylinder::area()
{
return 2 * pi * radius * height + 2 * pi * radius * radius;
}
double CCylinder::volume()
{
return pi * radius * radius * height;
}
void main()
{
CSolid *p;
double area, volume;
CCube box(5);
p = &box;
area = p->area();
volume = p->volume();
cout << "正方形的边长为:5" << endl;
cout << "面积为:" << area << endl;
cout << "体积为:" << volume << endl;
CBall ball(2.1);
p = &ball;
area = p->area();
volume = p->volume();
cout << "球的半径为为:2.1" << endl;
cout << "面积为:" << area << endl;
cout << "体积为:" << volume << endl;
CCylinder cylinder(3, 5.4);
p = &cylinder;
area = p->area();
volume = p->volume();
cout << "圆柱的底面半径为为:3,高为:5.4" << endl;
cout << "面积为:" << area << endl;
cout << "体积为:" << volume << endl;
system("pause");
}
输出结果:
面积为:150
体积为:125
球的半径为为:2.1
面积为:55.4177
体积为:29.0943
圆柱的底面半径为为:3,高为:5.4
面积为:158.336
体积为:152.681
请按任意键继续. . .