/* *Copyright(c)2014,烟台大学计算机学院学生 *All rights reserved. *文件名称: *作者:马广明 *完成日期:2014 年 5 月 27 日 *版本号:v1.0 *问题描述:求各种立体体积。 *输入描述:无。 *程序输出:正方体,球体,圆柱体面积及体积 *问题分析: *算法设计: */ #include <iostream> using namespace std; const double pi=3.1415926; class CSolib { public: virtual double area()=0; virtual double volume()=0; }; class CCube:public CSolib { public: CCube(double bc):bianchang(bc){} virtual double area(); virtual double volume(); private: double bianchang; }; class CBall:public CSolib { public: CBall(double R):r(R){} virtual double area(); virtual double volume(); private: double r; }; class CCylinde:public CSolib { public: CCylinde(double R,double H):r(R),h(H){} virtual double area(); virtual double volume(); private: double r,h; }; double CCube::area() { return 6*bianchang*bianchang; } double CCube::volume() { return bianchang*bianchang*bianchang; } double CBall::area() { return 4*pi*r*r; } double CBall::volume() { return 4/3*pi*r*r*r; } double CCylinde::area() { return 2*pi*r*r+2*pi*r*h; } double CCylinde::volume() { return pi*r*r*h; } int main() { CSolib *pt; CCube ccube(5); CBall cball(3.5); CCylinde ccylinde(3.5,5); pt=&ccube; cout<<"正方体面积:"<<pt->area()<<endl; cout<<"正方体体积:"<<pt->volume()<<endl; pt=&cball; cout<<"球体面积:"<<pt->area()<<endl; cout<<"球体体积:"<<pt->volume()<<endl; pt=&ccylinde; cout<<"圆柱体面积:"<<pt->area()<<endl; cout<<"圆柱体体积:"<<pt->volume()<<endl; return 0; }
立体类的面积和体积--虚函数
时间: 2024-10-12 14:51:07