利用基类、派生类编写一个程序计算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;
}