版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年合肥市轨道交通集团有限公司招聘考试真题
- 2025年江苏省烟草专卖局(公司)真题
- 崇州市卫生健康局下属事业单位招募医疗卫生辅助岗位考试真题2025
- 哈尔滨市绥化路学校扩建项目水土保持方案报告表
- 主题词 10 想象世界-备战2022年中考语文之“真题+模拟”主题作文专项训练(原卷版)
- 市场主体信用修复管理实施细则
- 机关干部推-荐考察不深入问题整改措施
- 教师资格证管理条例
- 关于加强机关机要工作规范化管理的指导意见
- 机关单位否定报备制度
- 校园消防隐患排查整治
- 产业园运营运作方案
- 2026成都环境投资集团有限公司下属子公司招聘工艺管理岗等岗位21人笔试题库及答案详解【真题汇编】
- 决胜分班考:2026江苏省新高一入学摸底测试全科高频考点与模拟训练
- GB/T 24026-2026环境标志和声明足迹信息交流的原则、要求和指南
- 国企中层干部竞聘测试题库(+答案)
- 施工暖通管道安装方案
- 湖北新八校2026届高三第二次联考(二模)语文试题及参考答案
- 家家悦超市成本控制策略与实践研究
- 永辉超市门店SOP标准作业流程制度规定
- 2026年基层应急管理规范考试试题及答案
评论
0/150
提交评论