问题及代码:
/*
*Copyright (c) 2014,烟台大学计算机学院
*All rights reserved.
*文件名称:lily.cpp
*作者:李莉
*完成日期:2015年5月18日
*版本号:v1.0
*
*问题描述:先建立一个Point(点)类,包含数据成员x,y(坐标点),实现需要的成员函数,并设计main函数完成测试
以Point为基类,派生出一个Circle(圆)类,增加数据成员r(半径),以及求面积的成员函数area,实现其他需要的成员函数,设计main函数完成测试
再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高),,以及求圆柱表面积的成员函数area和求圆柱体积的成员函数volume,实现需要的成员函数,并设计main函数完成测试。
*程序输入:无输入
*程序输出:如结果图
*/
#include <iostream>
using namespace std;
class Point
{
public:
Point(double x=0,double y=0);
void setPoint(double,double);
double getX( ) const {return x;}
double getY( ) const {return y;}
friend ostream & operator<<(ostream &,const Point &);
protected:
double x,y;
};
Point::Point(double a,double b)
{
x=a;
y=b;
}
void Point::setPoint(double a,double b)
{
x=a;
y=b;
}
ostream & operator<<(ostream &output,const Point &p)
{
output<<"["<<p.x<<","<<p.y<<"]"<<endl;
return output;
}
class Circle:public Point
{
public:
Circle(double x=0,double y=0,double r=0);
void setRadius(double);
double getRadius( ) const;
double area ( ) const;
friend ostream &operator<<(ostream &,const Circle &);
protected:
double radius;
};
Circle::Circle(double a,double b,double r):Point(a,b),radius(r){ }
void Circle::setRadius(double r)
{
radius=r;
}
double Circle::getRadius( ) const
{
return radius;
}
double Circle::area( ) const
{
return 3.14159*radius*radius;
}
ostream &operator<<(ostream &output,const Circle &c)
{
output<<"Center=["<<c.x<<", "<<c.y<<"], r="<<c.radius<<", area="<<c.area( )<<endl;
return output;
}
class Cylinder:public Circle
{
public:
Cylinder (double x=0,double y=0,double r=0,double h=0);
void setHeight(double);
double getHeight( ) const;
double area( ) const;
double volume( ) const;
friend ostream& operator<<(ostream&,const Cylinder&);
protected:
double height;
};
Cylinder::Cylinder(double a,double b,double r,double h) :Circle(a,b,r),height(h){}
void Cylinder::setHeight(double h)
{
height=h;
}
double Cylinder::getHeight( ) const
{
return height;
}
double Cylinder::area( ) const
{
return 2*Circle::area( )+2*3.14159*radius*height;
}
double Cylinder::volume() const
{
return Circle::area()*height;
}
ostream &operator<<(ostream &output,const Cylinder& cy)
{
output<<"Center=["<<cy.x<<","<<cy.y<<"], r="<<cy.radius<<", h="<<cy.height
<<"\narea="<<cy.area( )<<", volume="<<cy.volume( )<<endl;
return output;
}
int main( )
{
Cylinder cy1(3.5,6.4,5.2,10);
cout<<"\noriginal cylinder:\nx="<<cy1.getX( )<<", y="<<cy1.getY( )<<", r="
<<cy1.getRadius( )<<", h="<<cy1.getHeight( )<<"\narea="<<cy1.area()
<<",volume="<<cy1.volume()<<endl;
cy1.setHeight(15);
cy1.setRadius(7.5);
cy1.setPoint(5,5);
cout<<"\nnew cylinder:\n"<<cy1;
return 0;
}
运行结果:
心得体会:
原谅我的偷懒吧