问题描述:
按以下的提示,由基类的设计和测试开始,逐渐地完成各个类的设计,求出圆格柱体的表面积、体积并输出并且完成要求的计算任务:
(1)先建立一个Point(点)类,包含数据成员x,y(坐标点),实现需要的成员函数,并设计main函数完成测试;
(2)以Point为基类,派生出一个Circle(圆)类,增加数据成员r(半径),以及求面积的成员函数area,实现其他需要的成员函数,设计main函数完成测试;
(3)再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高),,以及求圆柱表面积的成员函数area和求圆柱体积的成员函数volume,实现需要的成员函数,并设计main函数完成测试。
要求编写程序,设计出各类中“需要的成员函数”,包括构造函数、析构函数、修改数据成员和获取数据成员的公共接口、用于输出的重载运算符“<<”函数等。
(提示:此任务可以分为三个子任务分成若干步骤进行。先声明基类,再声明派生类,逐级进行,分步调试。——这种方法适用于做任何的项目)
代码:
#include <iostream> const double pi=3.14159; using namespace std; class CPoint{ protected: double x; double y; public: CPoint(double a,double b):x(a),y(b){} double get_x(){ return x; } double get_y(){ return y; } void alter(double a,double b){ x=a; y=b; } friend ostream&operator<<(ostream&out, CPoint& a); }; ostream&operator<<(ostream&out, CPoint&a){ cout<<"点坐标\n"; cout<<"("<<a.get_x()<<","<<a.get_y()<<")"; return out; } class Circle:public CPoint{ protected: double r; public: Circle(double a,double b,double c):CPoint(a,b){r=c;} double get_r(){return r;} double area(){return pi*r*r;} double get_x(){ return x; } double get_y(){ return y; } friend ostream&operator<<(ostream&out,Circle&a); }; ostream&operator<<(ostream&out,Circle&a){ cout<<"圆的半径:"<<a.get_r()<<"\t圆心:"; cout<<"("<<a.get_x()<<","<<a.get_y()<<")"; cout<<"\t面积:"<<a.area()<<'\12'; } class Cylinder:public Circle{ protected: double h; public: Cylinder(double a,double b,double c,double d):Circle(a,b,c){h=d;} double get_h(){return h;} double get_r1(){return r;} double area1(){return pi*r*r;} double volume(){return area()*h;} double get_x1(){ return x; } double get_y1(){ return y; } friend ostream&operator<<(ostream*out,Cylinder&c); }; ostream&operator<<(ostream&out,Cylinder&c){ cout<<"圆柱底面积:"<<c.area1()<<"\t圆柱底面圆半径:"<<c.get_r1(); cout<<"\n圆底面圆圆心:"; cout<<"("<<c.get_x1()<<","<<c.get_y1()<<")"; cout<<"\t圆柱的高:" <<c.get_h()<<"\t圆柱体积:"<<c.volume(); } int main() { CPoint a(4,4); cout<<a<<'\12'; a.alter(3,7); cout<<a<<'\12'; Circle b(3,7,7); cout<<b; Cylinder c(3,7,7,10); cout<<c; return 0; }
运行结果:
时间: 2024-11-08 15:13:22