(3)再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高),,以及求圆柱表面积的成员函数area和求圆柱体积的成员函数volume,实现需要的成员函数,并设计main函数完成测试。
代码
#include<iostream>
#include<Cmath>
using namespace std;
class Point
{
protected:
double x,y;
public:
Point(double xx,double yy):x(xx),y(yy){}
double getx()
{
return x;
}
double gety()
{
return y;
}
void show1();
};
void Point::show1()
{
cout<<"底面圆心坐标:"<<"("<<x<<","<<y<<")"<<endl;
}
class Circle:public Point
{
protected:
double r,area;
public:
Circle(double xx,double yy,double rr):Point(xx,yy),r(rr){}
double getarea();
void show2();
double getr()
{
return r;
}
};
double Circle::getarea()
{
area=r*r*3.14;
return area;
}
void Circle::show2()
{
show1();
cout<<"底面积:"<<getarea()<<endl;
}
class Cylinder:public Circle
{
protected:
double h,volume;
public:
Cylinder(double xx,double yy,double rr,double hh):Circle(xx,yy,rr),h(hh){}
double getvolume();
friend ostream &operator<<(ostream &out,Cylinder &c);
double geth()
{
return h;
}
};
double Cylinder::getvolume()
{
volume=getarea()*h;
return volume;
}
ostream &operator<<(ostream &out,Cylinder &c)
{
c.show2();
out<<"体积:"<<c.getvolume()<<endl;
return out;
}
int main()
{
Cylinder c(2.2,3.3,4.4,5.5);
cout<<"该圆柱体的属性:"<<endl;
cout<<"底面半径:"<<c.getr()<<endl;
cout<<"高:"<<c.geth()<<endl;
cout<<c;
return 0;
}
运行结果:
时间: 2024-10-09 06:34:26