网站大量收购独家精品文档,联系QQ:2885784924

实验8 继承与派生要点.doc

  1. 1、本文档共9页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
实验 继承与派生 Person,并作为学生数据操作类Student和教师数据操作类Teacher的基类。 题目分析: 由题目可以得出需要设计一个Person基类,Teacher类和Student类都是由Person类派生的,即Teacher类和Student类都是由Person类继承而来,并且Teacher类和Student类都有编号和姓名数据成员,可以把它们作为Person类的公有或保护数据成员。 程序示例: #includeiostream.h class Person { protected: char name[10]; int number; public: void input() { cinnamenumber; } void show() { coutname\tnumberendl; } }; class Student :public Person { char sclass[10]; float score; }; class Teacher :public Person { char dept[10]; char title[6]; }; void main() { Student s1; Teacher t1; coutPlease input the name and the number of a student:endl; s1.input(); s1.show(); coutPlease input the name and the number of a teacher:endl; t1.input(); t1.show(); } 注意:把input和show两个函数放在Person类中。 实验要求: 上机运行该程序。 为Teacher类编写系别和职称的输入/输出函数;为Student类编写班级和成绩的输入/输出函数。 2.熟悉不同方式下对基类成员的访问控制 【实例2】给出下面程序的执行结果。 #includeiostream.h class A { public: A (int i,int j) { a=i; b=j; } void move(int x,int y) { a+=x; b+=y; } void show() { cout(a,b)endl; } private: int a,b; }; class B : public A { public: B(int i,int j,int k,int l) : A(i,j) { x=k; y=l; } void show() { coutx,yendl; } void fun() { move(3,5); } void f1() { A::show(); } private: int x,y; }; void main() { A a(1,2); a.show(); B b(3,4,5,6); b.fun(); b.show(); b.f1(); } 运行结果: (1,2) (5,6)#includeiostream.h class Point { int x,y; public: Point (int xx,int yy) { x=xx; y=yy; } void add(int xa,int ya) { x+=xa; y+=ya; } void show() { coutx=x,y=yendl; } }; class Rect:private Point { int len,width; public: Rect (int x,int y,int ll,int ww) : Point (x,y) { len=ll; width=ww; } void showRect() { show(); coutlength=len,width=widthendl; } }; void main() { Rect rect(0,2,3,6); rect.add(4,5); rect.showRect(); } 题目分析: 一个类被私有继承之后,其成员在派生类中访问属性会变为private,因而在派生类的对象rect不能直接访问基类的成员函数add。有两种改正的方法:第一改变继承方式;第二在派生类中重新定义add函数。 实验要求: 上机运行该程序,分析给出的错误提示。 按照上面两种方法,改正程序,程序编译通过后,给出运行结果。 3.分析下列程序中的访问权限,并回答所提的问题 #includeiostream.h class A { int i1; publi

文档评论(0)

441113422 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档