标签:
1 /* 2 *Copyright (c)2014,烟台大学计算机与控制工程学院 3 *All rights reserved. 4 *文件名称:d.cpp 5 *作 者:张旺华 6 *完成日期:2015年6月1日 7 *版 本 号:v1.0 8 */ 9 #include <iostream> 10 11 using namespace std; 12 const double pi=3.1415926; 13 class Point 14 { 15 public: 16 Point (double X=0,double Y=0):x(X),y(Y){} 17 ~Point(); 18 void setPoint(double,double); 19 double getx()const {return x;}; 20 double gety()const {return y;}; 21 friend ostream &operator<<(ostream &output,Point & p); 22 protected: 23 double x,y; 24 }; 25 Point::~Point() 26 {} 27 void Point::setPoint(double a,double b) 28 { 29 x=a; 30 y=b; 31 } 32 ostream &operator<<(ostream &output,Point & p) 33 { 34 output<<"["<<p.x<<","<<p.y<<"]"; 35 return output; 36 } 37 class Circle: public Point 38 { 39 public : 40 Circle(double a=0,double b=0,double r=0); 41 ~Circle(); 42 void setCircle(double a,double b,double r); 43 void setRadius(double r) { R=r;} 44 double getRadius(){return R;} 45 double area()const {return pi*R*R;} 46 double girth()const {return pi*R*2;} 47 friend ostream &operator<<(ostream &output,Circle & c); 48 protected: 49 double R; 50 }; 51 Circle::~Circle(){} 52 void Circle::setCircle(double a,double b,double r) 53 { 54 Point(a,b); 55 R=r; 56 } 57 Circle::Circle(double a,double b,double r):Point(a,b),R(r){} 58 59 ostream &operator<<(ostream &output,Circle & c) 60 { 61 output<<"R="<<c.R<<" Center=["<<c.x<<", "<<c.y<<"], r="<<c.R<<" area="<<c.area()<<" girth="<<c.girth(); 62 } 63 class Cylinder:public Circle 64 { 65 public: 66 Cylinder (double x=0,double y=0,double r=0,double h=0);//构造函数 67 void setHeight(double); //设置圆柱高 68 double getHeight( ) const; //读取圆柱高 69 double area( ) const; //计算圆柱表面积 70 double volume( ) const; //计算圆柱体积 71 friend ostream& operator<<(ostream&,const Cylinder&);//重载运算符“<<” 72 protected: 73 double height; //圆柱高 74 }; 75 76 //定义构造函数 77 Cylinder::Cylinder(double a,double b,double r,double h) :Circle(a,b,r),height(h){} 78 79 //设置圆柱高 80 void Cylinder::setHeight(double h) 81 { 82 height=h; 83 } 84 85 //读取圆柱高 86 double Cylinder::getHeight( ) const 87 { 88 return height; 89 } 90 91 //计算圆柱表面积 92 double Cylinder::area( ) const 93 { 94 return 2*Circle::area( )+2*Circle::girth()*height; 95 } 96 97 //计算圆柱体积 98 double Cylinder::volume() const 99 { 100 return Circle::area()*height; 101 } 102 103 //重载运算符“<<” 104 ostream &operator<<(ostream &output,const Cylinder& cy) 105 { 106 output<<"Center=["<<cy.x<<","<<cy.y<<"], r="<<cy.R<<", h="<<cy.height 107 <<"\narea="<<cy.area( )<<", volume="<<cy.volume( )<<endl; 108 return output; 109 } 110 111 int main( ) 112 { 113 Cylinder cy1(3.5,6.4,5.2,10); 114 cout<<"\noriginal cylinder:\nx="<<cy1.getx( )<<", y="<<cy1.gety( )<<", r=" 115 <<cy1.getRadius( )<<", h="<<cy1.getHeight( )<<"\narea="<<cy1.area() 116 <<",volume="<<cy1.volume()<<endl; 117 cy1.setHeight(15); 118 cy1.setRadius(7.5); 119 cy1.setPoint(5,5); 120 cout<<"\nnew cylinder:\n"<<cy1; 121 return 0; 122 }
运行结果:
知识点运用及学习心得:
这个加强 对构造函数含有派生和继承关系的理解
标签:
原文地址:http://www.cnblogs.com/zhangwanghua/p/4544635.html