




版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
ObjectivesTounderstandthemechanismsofstaticanddynamicpolymorphismTobeabletodeclarevirtualfunctionsandknowhowtousethemTobeabletodefineanabstractbaseclass01WhatisPolymorphism?04AbstractBaseClasses02DynamicPolymorphismandVirtualFunctions03UnderstandingofVirtualFunctions05InheritingInterfaceandImplementation01WhatisPolymorphism?Polymorphismforanaddition(+)operator,a+
bi+
jcomplex1+complex2foraprint
function, voidprint(int);voidprint(int,char*);Forexample,Whatispolymorphism?Wordmeaning--manyformsPolymorphismmeansthatsomecodes(functions),operatorsorobjectsbehavedifferentlyindifferentcontextsusingauniformform.PolymorphismisoneofOOPkeyfeatures.Polymorphism-BindingBindingisanassociation,suchasbetweenidentifiers(variablesorfunctionnames)andoperations(atypeorthespecificfunctionbody).Allfunctionshaveauniqueaddress.So,whenthecompilerencountersafunctioncall,itreplacesthefunctioncallwithamachinelanguageinstructionthattellstheCPUtojumptotheaddressofthefunction.Polymorphism-BindingTherearetwotypesofbindingaccordingtothetimeatwhichabindingtakesplace:(1)Compile-timebinding(calledstatic
binding,earlybinding)
–staticpolymorphism(2)Run-timebinding(calleddynamicbinding,latebinding)–dynamicpolymorphismStaticBinding(Compile-Time)–StaticPolymorphismclass
baseClass{public:voidf(){cout<<"CallingbaseClass\n";}};class
derivedClass:public
baseClass{public:voidf(){cout<<"CallingderivedClass\n";}};intmain(){baseClassone;one.f();derivedClasstwo;two.f();return0;}Staticbindingmeansthecompilerisabletodirectlyassociatetheidentifiername(suchasafunctionorvariable)withamachineaddress.Result:CallingbaseClassCallingderivedClassStaticBinding–StaticPolymorphismResult:CallingbaseClassCallingbaseClassclass
baseClass{public:voidf(){cout<<"CallingbaseClass\n";}};class
derivedClass:public
baseClass{public:voidf(){cout<<"CallingderivedClass\n";}};voidfn(baseClass&bc){bc.f();}intmain(){baseClassone;fn(one);derivedClasstwo;fn(two);return0;}A
top-level
functionwithaparameterofbaseclassreferenceorpointeri.e.referredtoasthederived-to-baseconversion02DynamicPolymorphismandVirtualFunctionsDynamicBinding(Run-Time)–DynamicPolymorphismResult:CallingbaseClassCallingderivedClassclass
baseClass{public:virtual
voidf(){cout<<"CallingbaseClass\n";}};class
derivedClass:public
baseClass{public:voidf(){cout<<"CallingderivedClass\n";}};voidfn(baseClass&bc){bc.f();}intmain(){baseClassone;fn(one);derivedClasstwo;fn(two);return0;}DynamicBinding
referstolinkingafunctioncalltothecodethatwillbeexecutedonlyatruntime.Thecodeassociatedwiththeproceduredosenotknowuntiltheprogramisexecuted.virtualfunctionVirtualFunctionsShape+volume():int+print():voidCube-edge:int+volume():int+print():voidCuboidlength:intwidth:intheight:int+volume():int+print():voidCaseStudyDefineclassescubeandcuboidaccordingtothegivenUMLdiagram.Cube-edge:int+volume():int+print():voidCuboidlength:intwidth:intheight:int+volume():int+print():voidVirtualFunctionsclass
Shape{public:Shape(){}virtual
intvolume(){cout<<"Shape'svolume.\n";return0;}virtual
voidprint(){cout<<"Shape’sprint.\n";}};class
Cube:public
Shape{public:Cube(int
e):edge(e){}virtual
intvolume(){cout<<"Cube’svolume\n";returnedge*edge*edge;}voidprint(){cout<<edge<<endl;}private:int
edge;};class
Cuboid:public
Shape{public:Cuboid(int
l,int
w,int
h):length(l),width(w),height(h){}virtual
intvolume(){cout<<"Cubiod’svolume\n";returnlength*width*height;}voidprint(){cout<<length<<width<<height<<endl;}private:intlength,width,height;};voidfn(Shape&
s){
s.print();cout<<s.volume();}intmain(){Cubec1(10);Cuboidc2(10,20,30);fn(&c1);fn(&c2);return0;}intmain(){Cubec1(10);Cuboidc2(10,20,30);fn(c1);fn(c2);return0;}voidfn(Shape*s){
s->print();cout<<s->volume();}ExtensibilityShape+volume():int+print():voidCube-edge:int+volume():int+print():voidCuboidlength:intwidth:intheight:int+volume():int+print():voidSphere-radius:int+volume():int+print():voidBenefitofusingvirtualfunctionsExtensibilityclass
Sphere:public
Shape{public:Sphere(int
r):radius(r){}virtual
intvolume(){
cout<<"Sphere’svolume\n";
return3.14*(double)4*(double)radius*radius*radius/3;}virtual
voidprint(){cout<<radius<<endl;}private:intradius;};voidfn(Shape*s){
s->print();cout<<s->volume();}intmain(){Cubec1(10);Cuboidc2(10,20,30);Spheres(10);fn(&c1);fn(&c2);fn(&s);return0;}03UnderstandingofVirtualFunctionsTheWorkingPrincipleofVirtualFunctionsintmain(){Cubec1(10);cout<<"sizeofc1"<<sizeof(c1)<<endl;Cuboidc2(10,20,30);cout<<"sizeofc2"<<sizeof(c2)<<endl;return0;}(32-bitcompiler)sizeofc18sizeofc216VirtualFunctionTable—VTABLEThecompilercreatesasinglevirtualfunctiontable(VTABLE)foreachclassthatcontainsvirtualfunctions.ThecompileplacestheaddressesofvirtualfunctionsforthoseclassesintheVTABLE.Apointer(vptr)isplacessecretlyineachclasswithvirtualfunctions.ItpointstotheVTABLEforobjects.addressaddressaddressConversionsandInheritancevoidfn(Shape&
s){
s.print();cout<<s.volume();}intmain(){
Cubec1(10);
Cuboidc2(10,20,30);fn(c1);fn(c2);
return0;}intmain(){
Cubec1(10);
Shape&
s=c1;
s.print();cout<<s.volume();
Cuboidc2(10,20,30);
s=c2;
s.print();cout<<s.volume();return0;}derived-to-baseUnderstandingconversionsbetweenbaseandderivedclassesisessentialtounderstandinghowobject-orientedprogrammingworks.ConversionsandInheritancevoidfn(Shape*s){
s->print();cout<<s->volume();}intmain(){
Cubec1(10);
Cuboidc2(10,20,30);fn(&c1);fn(&c2);
return0;}intmain(){
Cubec1(10);
Shape*
s=&c1;
s->print();cout<<s->volume();
Cuboidc2(10,20,30);
s=&c2;
s->print();cout<<s->volume();
return0;}derived-to-baseConversionsandInheritancevoidmain(){
Shape
s;Cube
&c1=s;//errorCube
*c2=s;//error}Thisresultsinthatwemightattempttousec1orc2tousemembersthatdonotexistinShape.Thefactthatwecanbindareference(orpointer)toabase-classtypetoaderivedobjecthasacruciallyimportantimplication:Whenweuseareference(orpointer)toabase-classtype,wedon’tknowtheactualtypeoftheobjecttowhichthepointerorreferenceisbound.Thatobjectcanbeanobjectofthebaseclassoritcanbeanobjectofaderivedclass.ConversionsandInheritanceintmain(){
Cubec1(10);
Shape
s=c1;}ShapeCube’sdataCubeMemoryBecausetheCubeisignored,wesaythattheCubeportionofShapeissliceddown.intmain(){
Cubec1(10);
Shape
s;s=c1;}Shape(constShape&)Shape&operator=(constShape&)Theautomaticderived-to-baseconversionappliesonlyforconversionstoareferenceorpointertype.VirtualDectructorResult:ConstructingbaseclassConstructingderivedclassDosthinBase!BaseDestroyedConstructorcannotbevirtualfunction,butdestructoralwaysbevirtualfunction.class
Base{public:Base(){cout<<"Constructingbaseclass\n";}~Base(){cout<<"BaseDestroyed\n";}voidDoSomething(){cout<<"DosthinBase!\n";}};class
Derived:public
Base{public:Derived(){cout<<"Constructingderivedclass\n";}~Derived(){cout<<"Deriveddestroyed\n";}voidDoSomething(){cout<<"DosthinDerived!\n";}};intmain(){//upcastBase*pBase=new
Derived;pBase->DoSomething();deletepBase;return0;}BaseclasspointertothederivedclassobjectVirtualDectructorclass
Base{public:Base(){cout<<"Constructingbaseclass\n";}~Base(){cout<<"BaseDestroyed\n";}virtual
voidDoSomething(){cout<<"DosthinBase!\n";}};class
Derived:public
Base{public:Derived(){cout<<"Constructingderivedclass\n";}~Derived(){cout<<"Deriveddestroyed\n";}voidDoSomething(){cout<<"DosthinDerived!\n";}};intmain(){Base*pBase=new
Derived;//upcastpBase->DoSomething();deletepBase;}class
Base{public:Base(){cout<<"Constructingbaseclass\n";}virtual~Base(){cout<<"BaseDestroyed\n";}virtual
voidDoSomething(){cout<<"DosthinBase!\n";}};class
Derived:public
Base{public:Derived(){cout<<"Constructingderivedclass\n";}~Derived(){cout<<"Deriveddestroyed\n";}voidDoSomething(){cout<<"DosthinDerived!\n";}};Result:(withvirtual)ConstructingbaseclassConstructingderivedclassDosthinDerived!BaseDestroyedResult:ConstructingbaseclassConstructingderivedclassDosthinDerived!DeriveddestroyedBaseDestroyed04AbstractBaseClassesAbstractBaseClassesSomeclassesrepresentabstractconceptsforwhichobjectscannotexist,thatis,theycannotbeinstantiated,becauseatleastonefunctionintheseclassesdonotknowwhattobeimplemented.However,theyexistsextensivelyforinheritance,andmostlyusedasabaseclass.Theseclassesarecalledabstractbaseclasses.class
Shape{public:Shape(){}virtual
intvolume();virtual
voidprint();};AbstractBaseClassesAclasswhichcontainsoneormorepurevirtualfunctioniscalledabstractbaseclass.class
Shape{public:Shape(){}virtual
intvolume()=0;virtual
voidprint()=0;};PurevirtualfunctionAbstractbaseclassApurevirtualfunction
isavirtualfunctionwhichcontainsnodefinitioninthebaseclass.Youdeclareapurevirtualfunctionbyusingapurespecifier(=0)inthedeclarationofavirtualmemberfunctionintheclassdeclaration.AbstractBaseClassesclass
Shape{public:Shape(){}virtual
intvolume()=0;virtual
voidprint()=0;};intShape::volume(){return
0;}voidShape::print(){}wecanprovideadefinitionforapurevirtual.However,thefunctionbodymustbedefinedoutsidetheclass.Thatis,wecannotprovideafunctionbodyinsidetheclassforafunctionthatis=0.AbstractBaseClassesShapes;//error–cannotbeinstantiatedShape*s;//okShape&s;//okAnobjectpointerAnobjectreferenceYoucannotcreateanobjectofanabstractclasstype;However,youcanusepointers
orreferencestoabstractclasstypes.AbstractBaseClassesclass
Shape{public:Shape(){}virtual
intvolume()=0;};class
Cube:public
Shape{public:Cube(int
e):edge(e){}intvolume(){
cout<<"Cube’svolume\n";
returnedge*edge*edge;}private:
intedge;};class
Cuboid:public
Shape{public:
Cuboid(int
l,int
w,int
h):
length(l),width(w),height(h){}
intvolume(){
cout<<"Cubiod’svolume\n";
returnlength*width*height;}private:
intlength,width,height;};intmain(){Shape*s;Cubec1(10);Cuboidc2(10,20,30);fn(&c1);fn(&c2);return0;}voidfn(Shape*s){
cout<<s->volume();}05InheritingImplementationand
Inheriting
InterfaceMemberFunctionsandInheritancebase+f():int+g():voidderived+f():intDistinguishbetweeninheritinginterfaceandinheritingimplementation.Interface-Overriding-VirtualfunctionsImplementation-
MemberfunctionsoftheclassesThememberfunctionsofabaseclasscanbeinheritedbyitsderivedclassintwoways:(1)Whenaderivedclassneedstobeabletoprovideitsowndefinitionforoperations,thederivedclassneedstooverridethedefinitionofthoseinheritedfromthebaseclass-interface(2)itsderivedclassonlyinheritthosewithoutanychange-implementationOverloadingandOverridingclass
Base{public:virtual
intf()const{cout<<"Base::f()\n";return1;}virtual
voidf(string
s)const{cout<<s<<"isaparameterintheBaseclass\n";}virtual
voidg()const{cout<<"Base::g()\n";}};class
Derived1:public
Base{public:voidg()const{cout<<"Overridingg()inDerived1\n";}};intmain(){Derived1d1;intx=d1.f();d1.f("hello");d1.g();return0;}Result:Base::f()HelloisaparameterintheBaseclassOverridingg()inDerived1OverloadingandOverridingclass
Base{public:virtual
intf()const{cout<<"Base::f()\n";return1;}virtual
voidf(string
s)const{cout<<s<<"isaparameterintheBaseclass\n";}virtual
voidg()const{cout<<"Base::g()\n";}};class
Derived1:public
Base{public:voidg()const{cout<<"Overridingg()inDerived1\n";}virtual
intf()const{cout<<“Dervied1::f()\n";return1;}};intmain(){Derived1d1;intx=d1.f();d1.f("hello");//errord1.g();return0;}nomatchingfunctionforcallto'Derived1::f(constchar[6])
d1.Base::f("hello");//okAderivedclassmemberwiththesamenameasamemberofthebaseclasshidesthedirectuseofthebaseclassmember.class
Base{public:virtual
intf()const{cout<<"Base::f()\n";return1;}virtual
voidf(string
s)const{cout<<s<<"isaparameterintheBaseclass\n";}};OverloadingandOverridingclass
Base{public:virtual
voidg()const{cout<<"Base::g()\n";}};
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 物業(yè)防疫試題及答案
- 廣西壯族自治區(qū)南寧市聯(lián)考2024-2025學(xué)年高一下學(xué)期5月月考英語(yǔ)試題(解析版)
- 2025年湖南省邵陽(yáng)市邵東市振華中學(xué)中考一模英語(yǔ)試題(含答案無(wú)聽(tīng)力原文及音頻)
- 化學(xué)●全國(guó)甲卷丨2021年普通高等學(xué)校招生全國(guó)統(tǒng)一考試化學(xué)試卷及答案
- 2025產(chǎn)品代理合同模板
- 2025年中國(guó)塑身衣產(chǎn)品行業(yè)市場(chǎng)前景預(yù)測(cè)及投資價(jià)值評(píng)估分析報(bào)告
- Polyozellin-生命科學(xué)試劑-MCE
- Melleolide-L-生命科學(xué)試劑-MCE
- 2025屆高考物理大一輪復(fù)習(xí)課件 第九章 第46課時(shí) 實(shí)驗(yàn)十:觀察電容器的充、放電現(xiàn)象
- 2025屆高考物理大一輪復(fù)習(xí)課件 第七章 階段復(fù)習(xí)(三) 能量與動(dòng)量
- JT-T-1094-2016營(yíng)運(yùn)客車(chē)安全技術(shù)條件
- 基于EtherCAT的多軸運(yùn)動(dòng)控制系統(tǒng)的研究與設(shè)計(jì)
- 醫(yī)學(xué)檢驗(yàn)項(xiàng)目管理制度
- 08J925-3 壓型鋼板、夾芯板屋面及墻體建筑構(gòu)造(三)
- 小學(xué)英語(yǔ)祈使句練習(xí)題
- 光伏組件生產(chǎn)員工考核試卷
- 2024年昆明祿勸國(guó)有資本投資開(kāi)發(fā)集團(tuán)有限公司招聘筆試參考題庫(kù)含答案解析
- MOOC 兒童舞蹈創(chuàng)編-長(zhǎng)沙師范學(xué)院 中國(guó)大學(xué)慕課答案
- 粽子工藝流程圖
- 團(tuán)務(wù)知識(shí)講座課件
- 杏樹(shù)的日常護(hù)理措施
評(píng)論
0/150
提交評(píng)論