文档详情

第十次上机作业.doc

发布:2018-01-01约6.15千字共10页下载文档
文本预览下载声明
实验十六 继承和派生的基本概念 1.范例:定义一个继承与派生关系的类体系,在派生类中访问基类成员。先定义一个点类,包含x,y坐标数据成员,显示函数和计算面积的函数成员;以点为基类派生一个圆类, 增加表示半径的数据成员,重载显示和计算面积的函数;定义一个线段类,以两个点类对象作数据成员,定义显示、求面积及长度函数,线段类采用聚合方式,因为有两个端点, 不能用派生方式。编程测试所定义的类体系。 【程序】 ?#includeiostream #include cmath using namespace std; const PI=3.14159; class Point{ friend class Line; protected: double x,y; public: Point(){x=0;y=0;} Point(double xv,double yv){x=xv;y=yv;} double Area(){return 0;} void Show(){ coutx=x y=y\n; } }; class Circle:public Point{ double radius; public: Circle(){x=0;y=0;radius=0;} Circle(double xv,double yv,double vv):Point(xv,yv){ radius=vv; } Circle(Circle cir):Point(cir){ radius=cir.radius; } Circle operator=(Circle cir){ this-Point::operator=(cir); radius=cir.radius; return *this; } double Area(){ return PI*radius*radius; } void Show(){ coutx=x y=yradius=radius\n; } }; class Line{ Point start,end; public: Line(){} Line(double xv1,double yv1,double xv2,double yv2): start(xv1,yv1),end(xv2,yv2){} double GetLength(){ return sqrt((start.x-end.x)*(start.x-end.x)+(start.y-end.y)*(start.y-end.y)); } double Area(){return 0;} void Show(){ coutstart point:\n; start.Show(); coutend point:\n; end.Show(); } }; int main(){ Point pt(0,0); Circle cl1(100,100,10),cl2(cl1),cl3; Line ln1(0,0,100,100),ln2; cout点面积:pt.Area()\n; pt.Show(); coutcl1圆面积:cl1.Area()\n; cl1.Show(); coutcl2圆面积:cl2.Area()\n; cl2.Show(); cl3=cl1; coutcl3圆面积: cl3.Area() endl; cl3.Show(); cout线面积: ln1. Area()\t线长度:ln1. GetLength() endl; ln1.Show(); ln2.Show(); return 0; ? ? 【注意】 在Point 类中,将Line 类定义为友元,便于在Line 类中访问;Point 类的x和y 定义为Protected 访问权限,便于派生类访问。 注意派生类的构造函数中对基类数据成员的初始化方法(即 Circle(double xv,double yv,double vv):Point(xv,yv)), 以及构造函数中对对象成员的初始化方法(即 Line(double xv1,double yv1,double xv2,double yv2) : start(xv1,yv1),end(xv2,yv2){ } ) 【要求】 (1) 建立工程,录入上述程序,改变数据实验之。 (2) 修改Point 类的数据成员x ,y 的访问权限为private ,再运行,结果如何? (3) 如果不将Line 类设为 Point 类的友元,应采取什么措施?为哪个类增加数据或函数成员? ? 2
显示全部
相似文档