第五次实验参考代码

本文介绍了一个基于C++的简单几何形状类的设计与实现,包括矩形、圆、球体和柱体等基本几何体的周长、面积及体积的计算方法,并通过实例演示了这些类的功能。

仅供参考

/**********************************************************/ //Function : main,Geometric及其派生类 //parm : //comment : //return : void //Author : //date : 2011.11.13 /**********************************************************/ #include <iostream.h> #include <math.h> const double PI=3.14159; class Geometric{ public: Geometric() {} virtual double Get_Girth()=0; //周长 virtual double Get_Area()=0; //面积 virtual double Get_Volume()=0; //体积 virtual void print()=0; //输出 }; class Rectangle:public Geometric{ protected: double length,width; public: Rectangle(double l,double w):Geometric(),length(l),width(w){} double Get_Girth() { return 2 * (width+length); } double Get_Area() { return width * length; } double Get_Volume() { return 0.0; } void print() { cout<<"The Rectangle's Girth is:"<<Get_Girth()<<endl; cout<<"The Rectangle's Area is:"<<Get_Area()<<endl; } }; class Circle:public Geometric{ protected: double radius; public: Circle(double r):Geometric() { radius = r; } double Get_Girth() { return 2 * PI * radius; } double Get_Area() { return PI * radius * radius; } double Get_Volume() { return 0.0; } void print() { cout<<"The Circle's Girth is:"<<Get_Girth()<<endl; cout<<"The Circle's Area is:"<<Get_Area()<<endl; } }; class Ball:public Circle{ public: Ball(double r):Circle(r) {} double Get_Girth() { return 0; } double Get_Area() { return 4 * Circle::Get_Area(); } virtual double Get_Volume() { return 4.0 / 3 * Get_Area() * radius; } void print() { cout<<"The Ball's Area is:"<<Get_Area()<<endl; cout<<"The Ball's volume is:"<<Get_Volume()<<endl; } }; class Column:public Circle{ protected: double height; public: Column(double r,double h):Circle(r),height(h){} double Get_Area() { return Circle::Get_Girth() * height + 2 * Circle::Get_Area(); } double Get_Volume() { return Circle::Get_Area() * height; } void print() { cout<<"The Column's Area is:"<<Get_Area()<<endl; cout<<"The Column's volume is:"<<Get_Volume()<<endl; } }; void fun(Geometric &p) { p.print(); } void main() { double r,h,w,l; cout<<"Please input the radius and height:"<<endl; cin>>r>>h; Circle obj_Cir(r); fun(obj_Cir); Ball obj_Bal(r); fun(obj_Bal); Column obj_Col(r,h); fun(obj_Col); cout<<"Please input the length and width:"<<endl; cin>>l>>w; Rectangle obj_Rec(l,w); fun(obj_Rec); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值