例、要求利用抽象类和纯虚函数,编程设计一个程序计算正方体、球体和圆柱体的表面积和体积,具体要求如下:
1、设计一个抽象类为公共基类 ;
2、设计成员函数source_area( ),求表面积;
3、设计成员函数volume( ),求体积;
4、定义数据成员r;
5、派生类cube、sphere、cylinder分别表示正方体类、球体类和圆柱体类。
程序如下:
//头文件 #include <iostream> using namespace std; #define PI 3.141265 class Solid //定义抽象类 { protected: double r; double s, v; public: virtual double S() = 0; virtual double V() = 0; Solid(double a, double b, double c) { r = a; s = b; v = c; } }; class Cube :public Solid { public: Cube(double a, double b, double c) : Solid(a, b, c) { } double S() { s = 6 * r * r; return s; } double V() { v = r * r * r; return v; } }; class Sphere :public Solid { public: Sphere(double a, double b, double c) : Solid(a, b, c) { } double S() { s = 4 * PI * r * r; return s; } double V() { v = PI * r * r * r * 4 / 3; return v; } }; class Cylinder :public Solid { protected: double high; public: Cylinder(double h, double r, double a, double v) : Solid(r, a, v) { high = h; } double S() { s = 2 * PI * r * r + 2 * PI * r * high; return s; } double V() { v = PI * r * r * high; return v; } }; double source_area(Solid* p) { return p->S(); } double volume(Solid* p) { return p->V(); } //主函数 #include"头文件.h" #include <iostream> using namespace std; int main() { char a; double r0, h; cout << "请输入正方体的边长:" << endl; cin >> r0; Cube cube(r0, 0, 0); cout << "正方体的表面积为:" << source_area(&cube) << endl << "正方体的体积为:" << volume(&cube) << endl; cout << "-------------------------"; cout << "" << endl; cout << "请输入球体的半径:" << endl; cin >> r0; Sphere sphere(r0, 0, 0); cout << "球体的表面积为:" << source_area(&sphere) << endl << "球体的体积为:" << volume(&sphere) << endl; cout << "-------------------------"; cout << "" << endl; cout << "请输入圆柱体的的底面半径:" << endl; cin >> r0; cout << "请输入圆柱体的的高:" << endl; cin >> h; Cylinder cylinder(r0, h, 0, 0); cout << "球体的表面积为:" << source_area(&cylinder) << endl << "球体的体积为:" << volume(&cylinder) << endl; system("pause"); return 0; }
测试结果如下:
以上就是本次C++的全部内容,感谢您的阅读和支持,篇幅较长,若有表述或者代码中的不当之处,望指出!您的指出和建议能给作者带来很大的动力!!!