标签:style blog http io os ar 2014 sp on
写一个程序,定义抽象基类Shape,由它派生出3个派生类,Circle(圆形)、Rectangle(矩形)、Triangle(三角形)。用如下的main()函数,求出定义的几个几何体的面积和
程序代码
#include <iostream> using namespace std; class CSolid//立方体类 { public: //计算立方体的表面积 virtual double Area() = 0; //计算立方体的体积 virtual double Volume() = 0; }; //立方体类派生出正方体类 class CCube : public CSolid { public: CCube(double a) { this->a = a; } //计算正方体的表面积 virtual double Area() { return 6 * a * a; } //计算正方体的体积 virtual double Volume() { return a * a * a; } protected: int a;//正方体的边长 }; //立方体类派生出球体类 class CBall : public CSolid { public: CBall(double r) { this->r = r; } //计算球体的表面积 virtual double Area() { return 4 * 3.14 * r * r; } //计算球体的体积 virtual double Volume() { return 4 * 3.14 * r * r; } protected: double r; }; //立方体类派生出圆柱体类 class CCylinder : public CSolid { public: CCylinder(double r, double h) { this->r = r; this->h = h; } //计算圆柱体的表面积 virtual double Area() { return 2 * 3.14 * r * (r + h); } //计算圆柱体的体积 virtual double Volume() { return 3.14 * r * r * h; } protected: double r; double h; }; void main() { CSolid *p;//立方体对象指针 double s,v;//分别保存表面积和体积 //正方体 CCube x(30); cout<<"正方体体边长为 30 "<<endl; p=&x; s=p->Area( ); v=p->Volume( ); cout<<"表面积:"<<s<<endl; cout<<"体积:"<<v<<endl; cout<<endl; //球 CBall y(4.5); cout<<"球体半径为 4.5 "<<endl; p=&y; s=p->Area( ); v=p->Volume( ); cout<<"表面积:"<<s<<endl; cout<<"体积:"<<v<<endl; cout<<endl; //圆柱体 CCylinder z(10,20); cout<<"圆柱体底面半径、高分别为 10, 20"<<endl; p=&z; s=p->Area( ); v=p->Volume( ); cout<<"表面积:"<<s<<endl; cout<<"体积:"<<v<<endl; cout<<endl; system("pause"); }
执行结果:
标签:style blog http io os ar 2014 sp on
原文地址:http://blog.csdn.net/u010105970/article/details/39482469