/* *Copyright (c)2014,烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:d.cpp *作 者:张旺华 *完成日期:2015年6月1日 *版 本 号:v1.0 */ #include <iostream> using namespace std; const double pi=3.1415926; class Point { public: Point (double X=0,double Y=0):x(X),y(Y){} ~Point(); void setPoint(double,double); double getx()const {return x;}; double gety()const {return y;}; friend ostream &operator<<(ostream &output,Point & p); protected: double x,y; }; Point::~Point() {} void Point::setPoint(double a,double b) { x=a; y=b; } ostream &operator<<(ostream &output,Point & p) { output<<"["<<p.x<<","<<p.y<<"]"; return output; } class Circle: public Point { public : Circle(double a=0,double b=0,double r=0); ~Circle(); void setCircle(double a,double b,double r); void setRadius(double r) { R=r;} double getRadius(){return R;} double area()const {return pi*R*R;} double girth()const {return pi*R*2;} friend ostream &operator<<(ostream &output,Circle & c); protected: double R; }; Circle::~Circle(){} void Circle::setCircle(double a,double b,double r) { Point(a,b); R=r; } Circle::Circle(double a,double b,double r):Point(a,b),R(r){} ostream &operator<<(ostream &output,Circle & c) { output<<"R="<<c.R<<" Center=["<<c.x<<", "<<c.y<<"], r="<<c.R<<" area="<<c.area()<<" girth="<<c.girth(); } 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*Circle::girth()*height; } //计算圆柱体积 double Cylinder::volume() const { return Circle::area()*height; } //重载运算符“<<” ostream &operator<<(ostream &output,const Cylinder& cy) { output<<"Center=["<<cy.x<<","<<cy.y<<"], r="<<cy.R<<", 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; }
原文地址:http://blog.csdn.net/wh201458501106/article/details/46314757