问题及代码:
/*Copyright (c)2016,烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:main.cpp *作 者:王艺霖 *完成日期:2016年5月9日 *版 本 号:v1.0 *问题描述:再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高),,以及求圆柱表面积的成员函数area和求圆柱体积的成员函数volume,实现需要的成员函数,并设计main函数完成测试。 *输入描述: *输出描述: */ #include <iostream> using namespace std; class Point { public: Point(double x=0,double y=0); void show(); protected: double x,y; }; Point::Point(double a,double b) { x=a; y=b; } void Point::show() { cout<<"["<<x<<","<<y<<"]"<<endl; } class Circle:public Point { public: Circle(double x=0,double y=0,double r=0); double area ( ); void show(); protected: double radius; }; Circle::Circle(double a,double b,double r):Point(a,b),radius(r) { } double Circle::area( ) { return 3.14159*radius*radius; } void Circle::show() { cout<<"Center=("<<x<<", "<<y<<"), r="<<radius<<", area="<<area( )<<endl; } class Cylinder:public Circle { public: Cylinder(double x=0,double y=0,double r=0,double h=0); double area(); void show(); double volume(); protected: double height; }; Cylinder::Cylinder(double a,double b,double r,double h):Circle(a,b,r),height(h){} double Cylinder::area() { return 2*Circle::area()+2*3.14159*radius*height; } double Cylinder::volume() { return Circle::area()*height; } void Cylinder::show() { cout<<"圆心:["<<x<<","<<y<<"], r="<<radius<<", h="<<height<<"\narea="<<area( )<<", volume="<<volume( )<<endl; } int main( ) { Cylinder c(3.5,6.4,5.2,10); c.area(); c.volume(); c.show(); return 0; }
运行结果:
学习心得:
内容都差不多,弄懂原理就行。