实验目的:
【任务4】设计一个抽象类CSolid,含有两个求表面积及体积的纯虚函数。设计个派生类CCube、CBall、CCylinder,分别表示正方体、球体及圆柱体。在main()函数中,定义基类的指针p(CSolid *p;),利用p指针,输出正方体、球体及圆柱体对象的表面积及体积。
实验代码:
#include <iostream>
using namespace std;
class CSolid
{
public:
virtual double area() const = 0;
virtual double volume() const = 0;
};
class CCube:public CSolid
{
public:
CCube(float lengh, float wide, float high);
virtual double area() const {return lengh * wide + lengh * high + wide * high;}
virtual double volume() const {return lengh * wide * high;}
private:
double lengh;
double wide;
double high;
};
CCube::CCube(float lengh, float wide, float high)
{
this->lengh = lengh;
this->wide = wide;
this->high = high;
}
class CBall:public CSolid
{
public:
CBall(double R) {this->R = R;}
virtual double area() const {return 4 * 3.14 * R * R;}
virtual double volume() const {return (double)3 / 4 * 3.14 * R * R * R;}
private:
double R;
};
class CCylinder:public CSolid
{
public:
CCylinder(double R, double high) {this->R = R; this->high = high;}
virtual double area() const {return 3.14 * R * R + 2 * 3.14 * R * high;}
virtual double volume() const {return 3.14 * R * R * high;}
private:
double R;
double high;
};
int main()
{
CCube cube(3, 4, 5);
CSolid *cs = &cube;
cout << "正方体的表面积为: " << cs->area() << endl;
cout << "正方体的体积为: " << cs->volume() << endl;
CBall ball(2);
cs = &ball;
cout << "球体的表面积为: " << cs->area() << endl;
cout << "球体的体积为: " << cs->volume() << endl;
CCylinder cylinder(2, 4);
cs = &cylinder;
cout << "圆柱体的表面积为: " << cs->area() << endl;
cout << "圆柱体的体积为: " << cs->volume() << endl;
system("pause");
return 0;
}
实验结果:
正方体的表面积为: 47
正方体的体积为: 60
球体的表面积为: 50.24
球体的体积为: 18.84
圆柱体的表面积为: 62.8
圆柱体的体积为: 50.24
请按任意键继续. . .
实验心得:
嗯~整体代码和实验三十分的类似,大体的思路也和实验三有异曲同工之感,编写上,也感觉像是在写实验三的翻版,只是,唯一的不同就在于最后的输出上,略有不同,其他的嘛~真的,没什么区别了吧,也是再考察抽象类,也是单一的抽象类,当然啊,换句话说,实验三会做了,实验四应该也不是问题吧,也是比较简单的题目,也花不了多少时间就可以搞定!