12.继承和派生讲解.ppt

  1. 1、本文档共67页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
第12章 继承和派生 ;第12章 继承和派生;12.1.1 继承的概念;类层次关系图;12.1.2 继承的特性;12.1.3 派生类的定义 ;例:;例: 人员类;;第12章 继承和派生;12.2.1 公有继承 ;[例Ex_PublicDerived] 派生类的公有继承示例;protected: void SetAge(int age) { this-age = age; } void ShowInfo() // 显示信息 { cout姓名:nameendl; cout性别:(sex==M?男:女)endl; cout年龄:ageendl; } private: char name[20]; // 姓名 char sex; // 性别 int age; // 年龄 };;class CStudent :public CPerson { public: CStudent(char *name, char *no, int age, char sex = M) :CPerson(name, age, sex) // 调用基类构造函数进行初始化 { strncpy(this-stuno, no, 20); } void SetScore( float s1, float s2, float s3 ) { score[0] = s1; score[1] = s2; score[2] = s3; total = s1 + s2 + s3; ave = total / (float)3.0; } void SetNoAndAge(char *no, int age) { strncpy(this-stuno, no, 20); this-SetAge( age ); } void ShowAll() { ShowInfo(); // 调用基类的成员函数 cout学号:stunoendl; cout三门成绩:score[0]\tscore[1]\tscore[2]endl; cout总成绩和平均分:total\taveendl; };private: char stuno[20]; // 学号 float score[3],ave, total; // 三门成绩、平均分和总分 }; int main() { CStudent one(LiMing, 19 ); // A one.SetScore( 90, 80, 84); // B one.ShowAll(); // 调用派生类的公有成员函数 one.SetNameAndSex(WangFang, W); // 调用基类的公有成员函数 one.SetNoAndAge 18 ); // 调用派生类的公有成员函数 one.ShowAll(); // 调用派生类的公有成员函数 return 0; };程序运行结果如下:;公有继承的派生类CStudent的成员及其访问权限;12.2.2 私有继承;[例Ex_PrivateDerived] 派生类的私有继承示例 ;protected: void SetAge(int age) { this-age = age; } void ShowInfo() // 显示信息 { cout姓名:nameendl; cout性别:(sex==M?男:女)endl; cout年龄:ageendl; } private: char name[20]; // 姓名 char sex; // 性别 int age; // 年龄 };;class CStudent :private CPerson { public: CStudent(char *name, char *no, int age, char sex = M) :CPerson(name, age, sex { strncpy(this-stuno, no, 20); } void SetScore( float s1, float s2, float s3 ) { score[0] = s1; score[1] = s2; score[2] = s3; total = s1 + s2 + s3; ave = to

文档评论(0)

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

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

1亿VIP精品文档

相关文档