版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
ObjectivesTounderstandinheritancefurtherTobeabletodefinederivedclassesindifferentinheritancemodes01MemberFunctionsofDerivedClasses03CaseStudy02InheritanceAccessControl01MemberFunctionsofDerivedClassesMemberfunctionsof
DerivedClassesclass
Employee{public:Employee(string
n,int
d){name=n;department=d;}voidprint()const{cout<<name<<department<<endl;}private:stringname;intdepartment;};class
Manager:public
Employee{public:Manager(string
n,int
d,string
rs):Employee(n,d),responsibility(rs){}private:stringresponsibility;};voidprint()const;Manager-responsibility:string+Manager(string,int,string)+management():voidEmployee-name:stringdepartment:string+Employee(string,int)+print():voidconstMemberFunctionsofDerivedClassesThememberfunctionsofthederivedclasscanalsobere-definedwhentheirnamesarethesameasonesofitsbaseclass.class
Manager:public
Employee{public:Manager(string&n,int
d,int
lvl):Employee(n,d),level(lvl){}voidprint()const;private:stringresponsibility;};void
Manager::print(){print();cout<<responsibility;}void
Manager::print(){Employee::print();cout<<responsibility;}void
Manager::print()const{cout<<name<<department;cout<<responsibility;}CannotaccesstheprivatemembersintheotherclassHowtodefinetheprintfunctioninclassManager?√MemberfunctionsofDerivedClassesvoid
Manager::print(){Employee::print();cout<<responsibility;}Functionoverridingisafeaturethat
allowsustouseafunctioninthederivedclassthatisalreadypresentinitsbaseclass.Whenyouwanttooverrideafunctionalityinthebaseclass,youusefunctionoverridingin
thederivedclass.Thismeansthattheimplementationofthebaseclassfunctionsismodified.FunctionOverridingFunctionOverridingvsOverloadingFunctionoverloadingprovidesmultipledefinitionsofthefunctionbychangingsignature,i.e.changenumbersofparametersanddatatypesofparameters,butthereturntypedoesn’tplayanyrole.Functionoverridingisredefinitionofthebaseclassfunctionwiththesamereturntypeandparameterlistinthederivedclass.voidprint();//okvoidprint(int);//okintprint(int);//errorstringprint(string);//okclass
base{public:voidfun(){cout<<
"base::fun()\n";}voidfun(int
a){cout<<
"base::fun(int)"
<<
a
<<endl;}};class
derived:public
base{public:voidfun(){cout<<
“derived::fun()\n";}voidfun(string
s){cout<<
"derived::fun(string)"
<<
s
<<endl;}};intmain(){baseb;b.fun();b.fun(4);derivedd;d.fun();d.fun("4");//d.fun(4);compileerrorreturn0;}OverridingmemberfunctionsOverloadingmemberfunctionsFunctionOverridingvsOverloading02InheritanceAccessControlAccessControlIfitisprivate,itsnamecanbeusedonlybymemberfunctionsandfriendsoftheclassinwhichitisdeclared.Ifitispublic,itsnamecanbeusedbyanyfunction.Ifitisprotected,itsnamecanbeusedonlybymemberfunctionsandfriendsoftheclassinwhichitisdeclaredandbymemberfunctionsandfriendsofclassesderivedfromthisclass.#Test-
a:int+
b:int#
c:intAccesscontrolinaclassareclassifiedintothreecategories:private,protectedorpublic.AccessControl–ProtectedMembersintmain(){Testta;ta.a=99;ta.b=100;ta.c=50;cout<<ta.geta()<<endl;cout<<ta.getb()<<endl;cout<<ta.c<<endl;return0;}//error-
private//error-protected//ok-publicTest-
a:int+
b:int#
c:intclass
Test{inta;protected:intb;public:intc;Test(){a=b=c=10;}intgeta(){returna;}intgetb(){returnb;}};class
dTest:public
Test{public:dTest():Test(){dt=20;}voidreset(){a=20;//errorb=20;}protected:intdt;};intmain(){dTestdtObj;cout<<dtObj.geta();cout<<dtObj.getb();cout<<dtObj.c;dtObj.reset();cout<<dtObj.getb();return0;}InheritanceAccessControlWhencreatingaderivedclassfromabaseclass,youcanusedifferentaccessspecifierstoinheritthedatamembersofthebaseclass.Thederivedclasscanaccessallthenon-privatemembersofitsbaseclass.Andthebaseclassmembersthatarenotaccessibletothememberfunctionsofderivedclassesshouldbedeclaredprivateinthebaseclass.Theaccessspecifiersthatareusedarepublic,privateandprotected.Whenderivingaclassfromabaseclass,thebaseclassmaybeinheritedthroughpublic,privateandprotectedinheritance.PublicInheritancesWheninheritingaclassfromapublicbaseclass,i.e.publicderivation,publicmembers
ofthebaseclassbecomepublicmembers
ofthederivedclass,protectedmembersofthebaseclassbecomeprotectedmembers
ofthederivedclass,andprivatemembersofthebaseclasskeepprivatemembersofthederivedclass.Publicderivationmakesthederivedclassasubtypeofitsbaseclass,itisthemostcommonformofderivation.PublicInheritanceclass
RichMan{public:RichMan();~RichMan();intcompany;//公司能被自己(基类),创业伙伴(友元),儿子(子类),其他人(外部)都可以访问private://钱和车子能被自己(基类),创业伙伴(友元)可以访问.儿子和外人都不给开int
money;intcar;protected:int
house;//房子能被自己(基类),创业伙伴(友元)可以访问,儿子(子类)也可以访问,外人是不可以访问};RichMancar:intmoney:int#house:int+company:int+RichMan()+~RichMan()class
LittleRichMan:public
RichMan{public:LittleRichMan();~LittleRichMan();};PublicInheritanceclass
LittleRichMan:public
RichMan{public:LittleRichMan();~LittleRichMan();};publicclass
LittleRichMan:public
RichMan{public:LittleRichMan();~LittleRichMan();intm_company;//baseclassprotected:
intm_house;//baseclassprivate:
intcar;//baseclass
intmoney;//baseclass};LittleRichMan+LittleRichMan()+~LittleRichMan()publicRichMancar:intmoney:int#house:int+company:int+RichMan()+~RichMan()ProtectedInheritancesWhenderivingfromaprotectedbaseclass,i.e.protectedderivation,publicandprotectedmembersofthebaseclassbecomeprotectedmembersofthederivedclass,andprivatemembersofthebaseclasskeepprivatemembersofthederivedclass.Protectedderivationisusefulinclasshierarchiesinwhichfurtherderivationisthenorm.ProtectedInheritancesclass
RichMan{public:RichMan();~RichMan();intcompany;//公司能被自己(基类),创业伙伴(友元),儿子(子类),其他人(外部)都可以访问private://钱和车子能被自己(基类),创业伙伴(友元)可以访问.儿子和外人都不给开int
money;intcar;protected:int
house;//房子能被自己(基类),创业伙伴(友元)可以访问,儿子(子类)也可以访问,外人是不可以访问};class
LittleRichMan:protected
RichMan{public:LittleRichMan();~LittleRichMan();};ProtectedInheritanceclass
LittleRichMan:protected
RichMan{public:LittleRichMan();~LittleRichMan();};protectedclass
LittleRichMan:protected
RichMan{public:LittleRichMan();~LittleRichMan();protected:int
m_company;//baseclassint
m_house;//baseclassprivate:int
car;//baseclassint
money;//baseclass};LittleRichMan+LittleRichMan()+~LittleRichMan()protectedRichMancar:intmoney:int#house:int+company:int+RichMan()+~RichMan()PrivateInheritancesWhenwederivefromaprivatebaseclass,i.e.privatederivation,publicandprotectedmembersofthebaseclassbecomeprivatemembersofthederivedclass.Privatemembersofthebaseclasskeepprivatemembersofthederivedclass.Privatederivationismostusefulwhendefiningaclassbyrestrictingtheinterfacetobasesothat
strongerguaranteescanbeprovided.PrivateInheritancesclass
RichMan{public:RichMan();~RichMan();intcompany;//公司能被自己(基类),创业伙伴(友元),儿子(子类),其他人(外部)都可以访问private://钱和车子能被自己(基类),创业伙伴(友元)可以访问.儿子和外人都不给开int
money;intcar;protected:int
house;//房子能被自己(基类),创业伙伴(友元)可以访问,儿子(子类)也可以访问,外人是不可以访问};class
LittleRichMan:private
RichMan{public:LittleRichMan();~LittleRichMan();};PrivateInheritanceclass
LittleRichMan:private
RichMan{public:LittleRichMan();~LittleRichMan();};privateclass
LittleRichMan:private
RichMan{public:LittleRichMan();~LittleRichMan();private:intm_company;//baseclassintm_house;//baseclassprivate:intcar;//baseclassintmoney;//baseclass};LittleRichMan+LittleRichMan()+~LittleRichMan()privateRichMancar:intmoney:int#house:int+company:int+RichMan()+~RichMan()DifferentInheritancesBaseclassAccesscontrolDerivedclassAccesscontrolGeneralusersprivateinheritanceprivateprivateNANAprotectedprivateANApublicprivateANAprotectedinheritanceprivateprivateNANAprotectedprotectedANApublicprotectedANApublicinheritanceprivateprivateNANAprotectedprotectedANApublicpublicAA03CaseStudyCaseStudyDesignasystemthatopensdifferentpostfixedfiles,e.g..txt,.pngandetc.textFile+openFile():voidFile#filename:string+openFile():voidbmpFile+openFile():voidDataabstractionForatextfilewith.txt,data:filenamefunction:openfileForanimagefilewith.png,data:filenamefunction:openfileAbstractcommonfeaturesCaseStudyclass
File{public:File(string&filename){fileName=filename;}voidopenFile(){cout<<"Openfile!\n";}protected:stringfileName;};class
textFile:public
File{public:textFile(string&filename):File(filename){}voidopenFile(){fileName=fileName+".txt";wstringtemp(fileName.begin(),fileName.end());LPCWSTRlpFile=temp.c_str();
//wstring->char*ShellExecute(NULL,L"open",L"notepad.exe",lpFile,NULL,SW_SHOW);}};#include
<Windows.h>
#include
<iostream>using
namespacestd;CaseStudyclass
bmpFile:public
File{public:bmpFile(string&filename):File(filename){}voidopenFile(){fileName=fileName+".png";wstringtemp(fileName.begin(),fileName.end());LPCWSTRlpFile=temp.c_str();ShellExecute(NULL,L"open",L"mspaint.exe",lpFile,NULL,SW_SHOW);}};intmain(){stringfilename="aa";textFiletext(filename);text.openFile();system("pause");bmpFilebmp(filename);bmp.openFile();return0;}SummaryDefinederivedclasses’memberfunctionsbyoverridingDistinguishbetweenfunctionoverloadingandoverridingKnowthreetypesofaccesscontrolinaclassKnowthedifferenceofprivate,protectedandpublicinheritancesObjectivesTounderstandtheconceptofmultipleinheritanceTounderstandwhyinheritanceambiguityoccursinmultipleinheritanceToknowthemechanismofvirtualinheritance01ClassHierarchyandMultipleInheritance03VirtualInheritance02InheritanceAmbiguity01ClassHierarchyandMultipleInheritanceClassHierarchiesTreestructureofclasshierarchyLatticestructureofclasshierarchySingleinheritanceandmultilevelinheritanceMultipleinheritanceandhybridinheritanceMultipleInheritanceBed+sleep():void+weight:intSofa+watchTV():void+weight:intSofaBed+foldOut():voidAclasscanhavemorethanonedirectbaseclass.Theuseofmorethanimmediatebaseclassisusuallycalledmultipleinheritance.CasestudyTherearetheBed,SofaandSofaBedclassesinaclasshierarchy.DefinitionsofDerivedClassesinMultipleInheritanceclassSofaBed:publicSofa,publicBed{//…};Bed+sleep():void+weight:intSofa+watchTV():void+weight:intSofaBed+foldOut():voidSyntaxtodefineaderivedclassofmultipleinheritanceConstructorsandDestructorsofMultipleInheritanceclass
Bed{public:Bed(){}voidsleep(){cout<<"Sleep..\n";}intweight;};class
Sofa{public:Sofa(){}voidwatchTV(){ cout<<"WatchingTV..\n";}intweight;};class
SofaBed:public
Bed,public
Sofa{public:SofaBed(){}voidfoldOut(){ cout<<"Foldout..\n";}};intmain(){SofaBedsBed;sBed.sleep();sBed.watchTV();sBed.foldOut();return0;}DerivedconstructorwithoutparametersSofaBed():Bed(),Sofa(){}ConstructorsandDestructorsofMultipleInheritancederived’sconstructor:base1’sconstructor,base3’sconstructor,base2’sconstructor{}Destroyingderivedobjects’sequence:derivedclass->base3->base2->base1classderived:publicbase1,publicbase2,publicbase3{};Constructingderivedclassobjects’sequence:base1->base2->base3->derivedSyntaxtodefineaconstructorofthederivedclassSyntaxtodefineadestructorofthederivedclassConstructingderivedobjects’sequenceaccordingtodeclaringsequenceofbaseclasses.derived’sdestructor{}ConstructorsandDestructorofMultipleInheritanceclass
Bed{public:Bed(int
w):weight(w){}voidsleep(){cout<<"Sleep..\n";}intweight;};class
Sofa{public:Sofa(int
w):weight(w){}voidwatchTV(){ cout<<"WatchingTV..\n";}intweight;};class
SofaBed:public
Bed,public
Sofa{public:SofaBed(int
w):Bed(w),Sofa(w){}voidfoldOut(){ cout<<"Foldout..\n";}};intmain(){SofaBedsBed(5);sBed.sleep();sBed.watchTV();sBed.foldOut();return0;}Derivedconstructorwithparameters02InheritanceAmbiguity
InheritanceAmbiguityintmain(){SofaBedsBed(5);sBed.sleep();sBed.watchTV();sBed.foldOut();
return0;}cout<<sBed.weight;//errorcout<<sBed.Bed::weight;Bed’s
weight?Sofa’s
weight?MultipleinheritanceambiguitiesWhenthebaseclassesmayhavememberfunctionswiththesamename,thefunctioncallofderivedclassobjectleadstoambiguity.Bed+sleep():void+weight:intSofa+watchTV():void+weight:intSofaBed+foldOut():voidInheritanceAmbiguitySingleinheritancemultipleinheritanceBed+sleep():voidSofa+watchTV():voidSofaBed+foldOut():voidFurniture-weight:intFurniture-weight:intBed+sleep():void+weight:intSofa+watchTV():void+weight:intSofaBed+foldOut():voidInheritanceAmbiguityThediamondproblemoccursinalatticestructure.HowtoavoidduplicatedBaseClasses?Bed+sleep():voidSofa+watchTV():voidSofaBed+foldOut():voidFurniture-weight:intDuplicationInheritanceclass
Furniture{intweight;public:Furniture(int
w):weight(w){}intgetWeight(){returnweight;}};class
Bed:public
Furniture{public:Bed(int
w):Furniture(w){}voidsleep(){cout<<"Sleep..\n";}};class
Sofa:public
Furniture{public:Sofa(int
w):Furniture(w){}voidwatchTV(){cout<<"WatchingTV..\n";}};class
SofaBed:public
Bed,public
Sofa{public:SofaBed(int
w):Bed(w),Sofa(w){}voidfoldOut(){cout<<"Foldout..\n";}};intmain(){SofaBedsBed(5);sBed.sleep();sBed.watchTV();sBed.foldOut();return0;}Result:Sleep..WatchingTV..Foldout..Constructingfurniture...ConstructingBed...Constructingfurniture...ConstructingSofa...ConstructingSofaBed...DuplicationInheritanceProblem:theduplicationofBaseClassesintmain(){SofaBedsBed(5);sBed.sleep();sBed.watchTV();sBed.foldOut();return0;}cout<<sBed.getWeight()<<endl;//error:
ambiguitySleep..WatchingTV..Foldout..Constructingfurniture...ConstructingBed...Constructingfurniture...ConstructingSofa...ConstructingSofaBed...Howtoresolvethisissue?03VirtualInheritanceVirtualInheritanceclass
Furniture{intweight;public:Furniture(int
w):weight(w){}intgetWeight(){returnweight;}};class
Bed:virtualpublic
Furniture{public:Bed(int
w):Furniture(w){}voidsleep(){cout<<"Sleep..\n";}};class
Sofa:virtualpublic
Furniture{public:Sofa(int
w):Furniture(w){}voidwatchTV(){cout<<"WatchingTV..\n";}};Class
SofaBed:public
Bed,public
Sofa{public:SofaBed(int
w):Furniture(w),Bed(w),Sofa(w){}voidfoldOut(){cout<<"Foldout..\n"
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 工地搭架施工方案模板(3篇)
- 元旦珠宝营销方案(3篇)
- 河南2026届下期高考适应性测试语文试题及参考答案
- 初中数学教研组工作计划(2篇)
- 电影与数字技术的融合趋势
- 深圳地铁复合地层中土压平衡盾构施工适应性的深度剖析与优化策略
- 深入探究MLDv2协议:从设计、实现到测试的全面剖析
- 淮安市施河镇教育装备产业集聚发展:模式、困境与突破路径
- 淞沪抗战时期上海国际救济会研究:组织、行动与影响
- 液晶-聚合物光栅激光器性能的多维度探究与优化策略
- 榆神能源有限责任公司横沟煤矿环境影响报告书
- 23秋国家开放大学《液压气动技术》形考任务1-3参考答案
- 2023年公安机关招警面试题及参考答案
- 粉末产品原辅材料入库检验规范
- 21ZJ111 变形缝建筑构造
- 电子线路设计、测试与实验(一)-华中科技大学中国大学mooc课后章节答案期末考试题库2023年
- 天然气管道置换记录表
- 五华区城中村改造实施办法
- 城市绿地系统专项规划说明书
- 《社会工作概论(第三版)》课件01 第一章 社会工作导论
- 工程教育认证学校培训课程专项测试卷含答案
评论
0/150
提交评论