类的继承和派生——求圆柱表面积
生活随笔
收集整理的这篇文章主要介绍了
类的继承和派生——求圆柱表面积
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
利用基类、派生类编写一个程序计算Point类、Circle类派生所得Cylinder类的表面积。
#include<iostream> using namespace std; #define PI 3.14 class Point{//定义Point类 private:int X,Y;//坐标 public:Point(int X=0,int Y=0){//带参数构造函数 this->X=X;this->Y=Y;} void ShowXY(){//显示坐标值 cout<<X<<" "<<Y<<endl;} };class Circle:protected Point{//由Point类派生出Circle类 PS:protected 比public 保护性更强所以选前者 protected:double r;//半径 public:Circle(double r,int X,int Y):Point(X,Y){//带参数构造函数 this->r=r;}double area(){//计算圆的表面积 return 2*PI*r*r;}void ShowC(){//显示 cout<<r<<endl;ShowXY();}}; class Cylinder:protected Circle{//由Circle派生出Cylinder类 private :double height;//圆柱高度 public:Cylinder(double height, double r, int X, int Y):Circle(r,X,Y){//带参数构造函数 this->height=height;}void ShowCY(){//显示 cout<<height<<" ";ShowC(); }double area(){//计算圆柱体表面积 return 2*Circle::area() +2*PI*r*height;//两个圆底的面积由Circle类函数进行计算 } }; int main(){Cylinder c(1,1,12,12);//定义圆柱体 c.ShowCY();//显示圆柱体信息 cout<<c.area()<<" "<<endl;//计算并返回结果 return 0; }总结
以上是生活随笔为你收集整理的类的继承和派生——求圆柱表面积的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: springboot下controll层
- 下一篇: SPECTRUM高速数据采集卡在RADA