C-程序設(shè)計(jì)教學(xué)課件CHAPTER-8-INHERITANCE_第1頁
C-程序設(shè)計(jì)教學(xué)課件CHAPTER-8-INHERITANCE_第2頁
C-程序設(shè)計(jì)教學(xué)課件CHAPTER-8-INHERITANCE_第3頁
C-程序設(shè)計(jì)教學(xué)課件CHAPTER-8-INHERITANCE_第4頁
C-程序設(shè)計(jì)教學(xué)課件CHAPTER-8-INHERITANCE_第5頁
已閱讀5頁,還剩81頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

C++ProgrammingCHAPTER8INHERITANCE1

8.1Introduction

8.2BasicConceptsandSyntax

8.3Public,Private,andProtectedInheritance

8.4MultipleInheritance

8.5ConstructorsandDestructorsUnderInheritance

8.6NameHiding

8.7VirtualInheritance28.1IntroductionInC++,wecanbuildanewclassbyderivingthenewclassfromanalreadyexistingclass.Themechanismforthisderivationisinheritance,andthederivedclassissaidtobeinheritedfromtheoriginalclass.38.1Introductionvehiclecarsaloncartruckestatecar48.1IntroductionInheritancepromotescodereusebecausethecodeinthebaseclassisinheritedbythesubclassandthusneednotberewritten.Youcanreusecodebycreatingnewclasses,butinsteadofcreatingthemfromscratch,youuseexistingclassesthatsomeoneelsehasbuiltanddebugged.58.1IntroductionInheritancealsoprovidesamechanismtoexpressthenaturalrelationshipsamongthecomponentsofaprogram.68.1Introductionanimalmonkeycatbirdliontigerleopard78.1IntroductionInheritanceisrequiredforpolymorphisminwhichtheparticularmethodtoinvokedependsontheclasstowhichtheobjectbelongs,buttheclasstowhichtheobjectbelongsisnotknownuntiltheprogramisexecuting.88.2BasicConceptsandSyntaxSyntax:classDerivedClass:InheritanceModeBaseClass{public://……protected://……private://……};98.2BasicConceptsandSyntaxExample:classPen{public:enumink{Off,On};voidset_status(ink);voidset_location(int,int);private:intx;inty;inkstatus;10};8.2BasicConceptsandSyntaxclassCPen:publicPen{public:voidset_color(int);private:intcolor;};118.2BasicConceptsandSyntaxintmain(){CPenpen1;return0;}PenCPenCPen128.2BasicConceptsandSyntaxRemarks:A)Themembers,whicharepublicinthebaseclass,arealsopublicinthederivedclass.B)Theprivatememberinabaseclassisvisibleonlyinthebaseclass.138.3Public,Private,andProtectedInheritancePublicInheritancePublicInheritanceRules:A)Thepublicmembersandprotectedmembersinthebaseclassarealsopublicandprotectedinthederivedclass,buttheprivatemembersinthebaseclasscan’tbeaccessedinthederivedclass.148.3Public,Private,andProtectedInheritancePublicInheritanceB)Thepublicmembersandtheprotectedmembersinthebaseclasscanbeaccessedbythemethodsofthederivedclass,buttheprivatememberscan’tbeaccessedbythemethodsofderivedclass.C)Onlythepublicmembersinthebaseclasscanbeaccessedbytheobjectsofthederivedclass.158.3Public,Private,andProtectedInheritancePublicInheritanceExample:classPoint{public://baseclassvoidInitP(floatxx=0,floatyy=0){X=xx;Y=yy;}voidMove(floatxOff,floatyOff){X+=xOff;Y+=yOff;}floatGetX(){returnX;}floatGetY(){returnY;}private:floatX,Y;16};8.3Public,Private,andProtectedInheritancePublicInheritanceclassRectangle:publicPoint//derivedclass{public://newpublicmethodofRectanglevoidInitR(floatx,floaty,floatw,floath){InitP(x,y);W=w;H=h;}//invokethepublicmethodofbase//classfloatGetH(){returnH;}floatGetW(){returnW;}private://newprivatemembersofRectanglefloatW,H;17};constructoranddestructorofPointarenotinherited!8.3Public,Private,andProtectedInheritancePublicInheritance#include<iostream>#include<cmath>usingnamespacestd;intmain(){Rectanglerect;rect.InitR(2,3,20,10);//accessthepublicmembersofthebaseclassbyobjectofderivedclassrect.Move(3,2);cout<<rect.GetX()<<','<<rect.GetY()<<','<<rect.GetW()<<','<<rect.GetH()<<endl;Output:5,5,20,1018return0;}8.3Public,Private,andProtectedInheritancePublicInheritanceRemark:Thedefaultconstructoranddestructorcannotbeinherited.198.3Public,Private,andProtectedInheritancePrivateInheritancePrivateInheritanceRules:A)Thepublicmembersandprotectedmembersinthebaseclassarebothprivateinthederivedclass,buttheprivatemembersinthebaseclasscannotbeaccessedinthederivedclass.208.3Public,Private,andProtectedInheritancePrivateInheritanceB)Thepublicmembersandtheprotectedmembersinthebaseclasscanbeaccessedbythemethodsofthederivedclass,buttheprivatememberscan’tbeaccessbythemethodsofderivedclass.C)Allthemembersinthebaseclasscan’tbeaccessedbytheobjectsofthederivedclass.21Example:classRectangle:privatePoint{public://newpublicmethodsofRectangle//accessthepublicmembersofthebaseclassvoidInitR(floatx,floaty,floatw,floath){InitP(x,y);W=w;H=h;}//redeclaretheinterfaceofbaseclass,why?voidMove(floatxOff,floatyOff){Point::Move(xOff,yOff);}floatGetX(){returnPoint::GetX();}floatGetY(){returnPoint::GetY();}floatGetH(){returnH;}floatGetW(){returnW;}private://newprivatemembersofRectanglefloatW,H;};22#include<iostream>#include<cmath>usingnamespacestd;intmain(){//onlythemembersofderivedclass//canbeaccessbyobjectsofderivedclassRectanglerect;rect.InitR(2,3,20,10);rect.Move(3,2);cout<<rect.GetX()<<','<<rect.GetY()<<','<<rect.GetW()<<','<<rect.GetH()<<endl;return0;}Output:5,5,10,20238.3Public,Private,andProtectedInheritanceProtectedInheritanceProtectedInheritanceRules:A)Thepublicmembersandprotectedmembersinthebaseclassarebothprotectedinthederivedclass,buttheprivatemembersinthebaseclasscannotbeaccessedinthederivedclass.248.3Public,Private,andProtectedInheritanceProtectedInheritanceB)Thepublicmembersandtheprotectedmembersinthebaseclasscanbeaccessedbythemethodsofthederivedclass,buttheprivatememberscan’tbeaccessbythemethodsofderivedclass.C)Allthemembersinthebaseclasscan’tbeaccessedbytheobjectsofthederivedclass.258.3Public,Private,andProtectedInheritanceProtectedInheritanceTotheobjectsofthederivedclass,protectedinheritanceisthesamewithprivateinheritance.Tothederivedclass,protectedinheritanceisthesamewithpublicinheritance.268.3Public,Private,andProtectedInheritanceProtectedInheritanceExample:classA{protected:intmain(){Aa;a.x=5;//wrongintx;}};278.3Public,Private,andProtectedInheritanceProtectedInheritanceExample:classA{protected:voidB::Function(){x=5;//rightintx;}}classB:publicA{public:voidFunction();28};8.3Public,Private,andProtectedInheritanceProtectedInheritancemembersinbaseclassinheritancemodeinderivedclasspublicprotectedpublicpublicpublicprotectedprivatepublicprotectedprivatepublicprotectedprivatepublicprotectedprotectedprotectedprivateprivateprivatecan’taccessprotectedprotectedcan’taccessprivateprivatecan’taccess298.3Public,Private,andProtectedInheritanceProtectedInheritanceExample:Ch8-2.textCh8-2answer.txt308.3Public,Private,andProtectedInheritanceCompatibleRulesCompatibleRulesAnobjectofderivedclass,whichispublicinheritedfromthebaseclass,canbeuseasaobjectofbaseclass:A)Objectsofbaseclasscanbeassignedbytheobjectofderivedclass.B)Referencesofbaseclasscanbeinitializedbytheobjectofderivedclass.318.3Public,Private,andProtectedInheritanceCompatibleRulesC)Pointersofbaseclasscanbeassignedbythepointerofderivedclass.D)Onlymembersofbaseclasscanbeaccessedbythepointersandobjectsofbaseclass.328.3Public,Private,andProtectedInheritanceCompatibleRulesExample:classBase{…};classDerived:publicBase{…};Baseb;Derivedd;b=d;Derivedd;Base*bptr=&d;Derivedd;Base&b=d;Derived*dptr;Base*bptr=dptr;338.3Public,Private,andProtectedInheritanceCompatibleRulesExample:#include<iostream>usingnamespacestd;classB0{public://Baseclassvoiddisplay(){cout<<"B0::display()"<<endl;}};348.3Public,Private,andProtectedInheritanceCompatibleRulesclassB1:publicB0{public:voiddisplay(){cout<<"B1::display()"<<endl;}};classD1:publicB1{public:voiddisplay(){cout<<"D1::display()"<<endl;}};voidfun(B0*ptr){35ptr->display();}8.3Public,Private,andProtectedInheritanceCompatibleRulesvoidmain(){B0b0;B1b1;D1d1;B0*p;p=&b0;fun(p);p=&b1;fun(p);p=&d1;fun(p);//objectofB0//objectofB1//objectofD1//pointerofB0//pointtoobjectofB0Output:B0::display()B0::display()B0::display()//pointtoobjectofB1//pointtoobjectofD1}368.3Public,Private,andProtectedInheritanceCompatibleRulesExercise:#include<iostream.h>classBase{public:voidf(){cout<<“excutingBase::f()\n”;}inta;};classDerived:publicBase{public:voidf(){cout<<“executingDerived::f()”;}inta;37};intmain(){Basex;x.a=20;x.f();cout<<“x.a=”<<x.a<<endl;Derivedy;y.a=40;y.Base::a=60;y.f();y.Base::f();cout<<“y.a=”<<y.a<<endl;cout<<“y.Base::a=”<<y.Base::a<<endl;Basez=y;cout<<“z.a=”<<z.a<<endl;return0;Output:executingBase::f()x.a=20executingDerived::f()executingBase::f()y.a=40y.Base::a=60z.a=60}388.4MultipleInheritanceYoucaninheritfromoneclass,soitwouldseemtomakesensetoinheritfrommorethanoneclassatatime.Inmultipleinheritance,aderivedclasshasmultiplebaseclasses.398.4MultipleInheritanceSyntax:classDerivedClass:InheritanceModeBaseClass1,InheritanceModeBaseClass2,...{//…};Remark:Therulesofinheritanceandaccessdon’tchangefromasingletoamultipleinheritancehierarchy.40Example:classA{public:voidsetA(int);voidshowA();private:inta;};classB{public:classC:publicA,privateB{public:voidsetB(int);voidshowB();voidsetC(int,int,int);voidshowC();private:private:intb;intc;41};};voidA::setA(intx){a=x;}voidB::setB(intx){b=x;}voidC::setC(intx,inty,intz){intmain(){setA(x);setB(y);c=z;Cobj;obj.setA(5);obj.showA();obj.setC(6,7,9);obj.showC();//obj.setB(6);wrong,why?//obj.showB();wrong,why?return0;}//......}428.5ConstructorsandDestructorsUnderInheritanceConstructorsunderInheritanceConstructorsunderInheritanceRules:A)Constructorsofbaseclasscan’tbeinherited.B)Membersofderivedclassshouldbeinitializedbyitsownconstructors.Membersofbaseclassshouldbeinitializedbytheconstructorsofbaseclass.C)Theargumentsoftheconstructorsofbaseclassshouldbeofferedbytheconstructorofderivedclass.438.5ConstructorsandDestructorsUnderInheritanceConstructorsunderInheritance

Syntax:DerivedClass::DerivedClassSingleInheritance(ArgumentListOfBase,ArgumentListOfDdrived):BaseClass(ArgumentListOfBase){//…};448.5ConstructorsandDestructorsUnderInheritanceConstructorsunderInheritanceOrderofConstructorcallsinSingleInheritance1)Constructorsofbaseclass.2)Constructorsofdatamembersinderivedclass.3)Constructorsofderivedclass.45Example:#include<iostream>usingnamespacestd;classB{public:B::B(){b=0;cout<<"B'sdefaultconstructorcalled."<<endl;}B::B(inti){B();B(inti);~B();voidPrint()const;b=i;cout<<"B'sconstructorcalled."<<endl;}B::~B(){private:intb;};cout<<"B'sdestructorcalled."<<endl;}voidB::Print()const{cout<<b<<endl;}46classC:publicB{public:C::C(){c=0;cout<<"C'sdefaultconstructorcalled."C();C(inti,intj);~C();voidPrint()const;<<endl;}C::C(inti,intj):B(i){private:c=j;cout<<"C'sconstructorcalled."<<endl;intc;};}C::~C(){voidC::Print()const{cout<<"C'sdestructorcalled."<<endl;}B::Print();cout<<c<<endl;}47voidmain(){Output:B'sconstructorcalled.C'sconstructorcalled.56C'sdestructorcalled.B'sdestructorcalled.Cobj(5,6);obj.Print();}Question:What’stheeffectof“C::C(inti,intj):B(i)”?488.5ConstructorsandDestructorsUnderInheritanceConstructorsunderInheritance

Syntax:DerivedClass::DerivedClassMultipleInheritance(ArgumentListOfBase1,…,ArgumentListOfBaseN,ArgumentListOfDdrived):BaseClass1(ArgumentListOfBase1),…,BaseClassN(ArgumentListOfBaseN)BaseClassn(ArgumentListOfBaseN){//…49};8.5ConstructorsandDestructorsUnderInheritanceConstructorsunderInheritanceArgumentsOfferingRules:A)Iftheconstructorsofbaseclassneednoarguments,constructorsofderivedclasscanbenoarguments.B)Iftheconstructorsofbaseclassneedarguments,constructorsofderivedclassshouldofferargumentstothem.508.5ConstructorsandDestructorsUnderInheritanceConstructorsunderInheritanceOrderofConstructorcallsinMultipleInheritance:1)Constructorsofbaseclasses,inorderoftheirdeclaration.2)Constructorsofdatamembersinderivedclass,inorderoftheirdeclaration.3)Constructorsofderivedclass.518.5ConstructorsandDestructorsUnderInheritanceConstructorsunderInheritanceExample:code.txt.code-answer.txt528.5ConstructorsandDestructorsUnderInheritanceConstructorsunderInheritance

Rules:A)IfthedefaultcopyconstructorisinvokedbytheobjectCopyConstructorsofderivedclass,thedefaultcopyconstructorofbaseclassisinvokedautomatically.B)Ifthereisauser-definedcopyconstructorofderivedclass,itshouldofferargumentstothecopyconstructorofbaseclass.538.5ConstructorsandDestructorsUnderInheritanceConstructorsunderInheritanceExample:C::C(C&c1):B(c1){//…}54Example:#include<iostream>usingnamespacestd;classB1//baseclassB1{public:classB2{public://baseclassB2B2(intj){cout<<"constructingB2"<<j<<endl;B1(inti){}};classB3{public://baseclassB3cout<<"constructingB1"<<i<<endl;}B3(){};cout<<"constructingB3*"<<endl;}};55classC:publicB2,publicB1,publicB3{public:C(inta,intb,intc,intd):B1(a),memberB2(d),memberB1(c),B2(b){}private:B1memberB1;B2memberB2;B3memberB3;};voidmain(){Output:constructingB22constructingB11constructingB3*constructingB13constructingB24constructingB3*Cobj(1,2,3,4);}568.5ConstructorsandDestructorsUnderInheritanceDestructorsunderInheritanceRules:A)Destructorscan’tbeinherited.B)Orderofdestructorsisoppositionofconstructors.57Example:#include<iostream>usingnamespacestd;classB1//baseclassB1{public:B1(inti)~B1(){cout<<"destructingB1"<<endl;}{cout<<"constructingB1"<<i<<endl;}};classB2//baseclassB2{public:B2(intj)~B2(){cout<<"destructingB2"<<endl;}{cout<<"constructingB2"<<j<<endl;}};classB3//baseclassB3{public:B3(){cout<<"constructingB3*"<<endl;}~B3(){cout<<"destructingB3"<<endl;}58};classC:publicB2,publicB1,publicB3{public:C(inta,intb,intc,intd):B1(a),memberB2(d),memberB1(c),B2(b){}private:Output:constructingB22constructingB11constructingB3*constructingB13constructingB24constructingB3*destructingB3destructingB2destructingB1destructingB3destructingB1destructingB2B1memberB1;B2memberB2;B3memberB3;};voidmain(){Cobj(1,2,3,4);}598.6NameHidingIfaderivedclassaddsamemberwiththesamenameasthememberinthebaseclass,thelocalmemberhidestheinheritedmember.60Example:#include<iostream>usingnamespacestd;classB1{public://baseclassB1intnV;voidfun(){cout<<"MemberofB1"<<endl;}};classB2{public://baseclassB2intnV;voidfun(){cout<<"MemberofB2"<<endl;}};classD1:publicB1,publicB2{public:intnV;//samenamewithbaseclassvoidfun(){cout<<"MemberofD1"<<endl;}//samenamewithbaseclass61};voidmain(){D1d1;d1.nV=1;//memberofD1isaccessedd1.fun();d1.B1::nV=2;//memberofB1isaccessedd1.B1::fun();d1.B2::nV=3;//memberofB2isaccessedd1.B2::fun();}628.7VirtualInheritanceAmbiguityAmbiguityInmultipleinheritance,ambiguityisaproblem.638.7VirtualInheritanceAmbiguityExample:classA{public:classC:publicA,piblicB{public:voidg();voidh();voidf();};classB{public:};Giventhedeclaration:Cc1;voidf();voidg()c1.f();//wrong,ambiguousc1.g();//right,namehiding64};8.7VirtualInheritanceAmbiguitySolutionstoambiguitySolution1:Scopingc1.A::f()orc1.B::f()658.7VirtualInheritanceAmbiguitySolution2:NameHidingclassC:publicA,piblicB{public:voidg();voidh();voidf1(){A::f();}voidf2(){B::f();}};668.7VirtualInheritanceVirtualBaseClassesVirtualBaseClassMultipleinheritancehierarchiescanbecomplex,whichmayleadtothesituationinwhichaderivedclassinheritsmultipletimesfromthesameindirectbaseclass.678.7VirtualInheritanceVirtualBaseClassesExample:classB{public:classC:publicB1,publicB2{public:intb;}classB1:publicB{private:intf();private:intd;intb1;};}classB2:publicB{private:intb2;68};8.7VirtualInheritanceVirtualBaseClassesBB1B2C698.7VirtualInheritanceVirtualBaseClassesbmembersofBmembersofB1b1bmembersofBmembersofCmembersofB2b2d708.7VirtualInheritanceVirtualBaseClassesambiguous:Cc;c.bc.B::bunambiguous:c.B1::bc.B2::bHowtosolvethedataredundancy?718.7VirtualInheritanceVirtualBaseClassesSyntax:classDerivedClass:virtualInheritanceModeBaseClass{//……}Remark:Inmultipleinheritancehierarchies,derivedclasshasonlyonesinglecopyofthebaseclassbyusingthekeywordvirtual.728.7VirtualInheritanceVirtualBaseClassesExample:classB{private:intb;};classB1:virtualpublicB{private:intb1;};classB2:virtualpublicB{private:intb2;};classC:publicB1,publicB2{private:floatd;}Ccobj;cobj.b;//thereisonlyonecopyofBinC738.7VirtualInheritanceVirtualBaseClassesBB1B2onlyonecopyofdatamemberandmethodsCB1membersb1B2membersCobjectb2dbBmembers748.7VirtualInheritanceVirtualBaseClassesExample:<<virtual>>B0nV:intfun()D1B1B2nV:intnV1:intnV2:intnVd:intB1::nV1:intB2::nV2:intfund():voidfun():voidD1nVd:int75fund():void8.7VirtualInheritanceVirtualBaseClasses#include<iostream>usingnamespacestd;classB0//baseclassB0{public:intnV;voidfun(){cout<<"MemberofB0"<<endl;}};classB1:virtualpublicB0//virtualinheritedfromB0{public:intnV1;};classB2:virtualpublicB0//virtualinheritedfromB0{public:intnV2;76};8.7VirtualInheritanc

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論