版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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";}};class
Derived1:public
Base{public:voidg()constoverride{cout<<"Overridingg()inDerived1\n";}};Overriding(Virtualfunctions)inderivedclassAfunctionfromaderivedclasswiththesamename,thesamesetofparametertypesandthesamereturningtypeasavirtualfunctioninabaseclass.FunctionoverloadinginbaseclassorderivedclassAnumberoffunctionswiththesamenameanddifferenttypesand/ornumbersofparametersintheargumentlistisreferredasfunctionoverloading.MemberFunctionsandInheritanceAderivedclassinheritseverymemberofitsbaseclassexcept:itsconstructorsanddestructorsitsoverloadedoperator(=)itsfriendsPolymorphismStaticbinding(compile-timebinding)-staticpolymorphism
C++matchedafunctioncallwiththecorrectfunctiondefinitionatcompiletime,e.g.overloadingfunctions,overloadingoperatorsDynamicbinding(run-timebinding)-dynamicpolymorphismThebindingoccursatprogramexecutiontime,thatis,thecompilermatchesafunctioncallwiththecorrectfunctiondefinitionatruntime,e.g.virtualfunctionsPolymorphismPolymorphismStaticBindingOperatorOverloadingCompileTimeDynamicBindingRunTimeFunctionOverloadingVirtualFunctionSummaryBeabletoknowwhatpolymorphismisBeabletodistinguishbetweenstaticbindinganddynamicbindingBeabletodefineavirtualfunctionBeabletounderstandabstractandconcertclassesBeabletothekeyfeaturesinobject-orientedprogrammingaredataabstraction,encapsulation,inheritance,anddynamicbindingObjectivesTounderstandthepurposeofgenericprogrammingToknowthemechanismoftemplatesTobeabletodefinefunctiontemplatesandinstantiatefunctiontemplatesTobeabletodefineclasstemplatesandinstantiateclasstemplates01IntroductiontoTemplates04ClassTemplates02FunctionTemplates03FunctionTemplateInstantiation05ClassTemplateInstantiation01IntroductiontoTemplatesWhatisaTemplate?Imaginethatwewanttowriteafunctiontofindthemaximumoneoftwovalues.Inpractice,we’dwanttodefineseveralsuchfunctions,eachofwhichwillfindthemaximumvalueofagiventype.CasestudyintmaxV(int
x,int
y){return(x>y)?x:y;}charmaxV(char
x,char
y){return(x>y)?x:y;}doublemaxV(double
x,double
y){return(x>y)?x:y;}#definemaxV(x,
y)((x>y)?x:y)Problem:Macropresentsthepossibilityforserioussideeffects:notypechecking,repetitiveoperationsandsoon.intmain(){inti=5,j=3;cout<<maxV(++i,j);return0;}Result:7TmaxV(Tx,Ty){return(x>y)?x:y;}Result:6TheConceptofTemplatesTemplatemechanismallowsatypetobeaparameterinthedefinitionofaclassorafunction.TmaxV(Tx,Ty){return(x>y)?x:y;}Templatesprovideasimplewaytorepresentawiderangeofgenericconceptsandsimplewaystocombinethem.Templatesarethefoundationforgenericprogramming.Atemplateisablueprintorformulaforcreatingclassesorfunctions.
TemplatesareoneofC++’scapabilitiesforsoftwarereusability.02FunctionTemplatesFunctionTemplatestemplate<typenameidentifier>,ortemplate<classidentifier>function_declaration(orfunction_definition);template<classT>TmaxV(Tx,Ty){return(x>y)?x:y;}Keywordtemplate<typenameT>TmaxV(Tx,Ty){return(x>y)?x:y;}typeidentifierintmaxV(int
x,int
y){return(x>y)?x:y;}charmaxV(char
x,char
y){return(x>y)?x:y;}doublemaxV(double
x,double
y){return(x>y)?x:y;}templateparameterlistkeywordCasestudySyntaxtodefineafunctiontemplateFunctionTemplatesAfunctiontemplatedefinesafamilyoffunctionsthatcanoperatewith
generictypes.Thisallowsustocreateafunctiontemplatewhosefunctionalitycanbeadaptedtomorethanonetypewithoutrepeatingtheentirecodeforeachtype.03FunctionTemplateInstantiationFunctionTemplatesInstantiationtemplate<typename
T>TmaxV(Tx,Ty);//declarationintmain(){cout<<maxV(3,4)<<endl;cout<<maxV(3.4,67.8)<<endl;cout<<maxV('s','x')<<endl;return0;}template<typename
T>//definitionTmaxV(T
x,T
y){return(x>y)?x:y;}Functiontemplateinstantiationfunction_name<type>(arguments);cout<<maxV<int>(3,4);cout<<maxV<double>(3.4,67.8);cout<<maxV<char>('s','x')Functiontemplateinstantiationisacreationof
aconcretefunction.FunctionTemplatesInstantiationWhenwecallafunctiontemplate,thecompiler(ordinarily)usestheargumentsofthecalltodeducethetemplateparameter(s)(T)forus.cout<<maxV(3,4)<<endl;cout<<maxV(3.4,67.8)<<endl;cout<<maxV('s','x')<<endl;Nocodeisgeneratedfromasourcefilethatcontainsonlytemplatedefinitions.Inorderforanycodetoappear,atemplatemustbeinstantiated:thetemplateargumentsmustbedeterminedsothatthecompilercangenerateanactualfunction.FunctionTemplateswithdifferentTypeParameterstemplate<typename
T1,typename
T2>T1getMin(T1
x,T2
y){return
x<y?x:(T1)y;}intmain(){inti=9,j=6;doublea=8.3,b=7.8;cout<<getMin(i,a);return0;}cout<<getMin<int,double>(i,a);template<typename
T1,T2>//errorT1getMin(T1
x,T2
y){return
x<y?x:(T1)y;}FunctionTemplatesandOverloadingBothoftheymakecodesmorecompactandconvenient.Functionoverloadingisnormallyusedtoperformsimilaroridenticaloperationsondifferenttypesofdata.Functiontemplates
areusedtoperformidenticaloperationsondifferenttypesofdata.FunctionTemplates
Overloadingtemplate<typename
T>voidSwap(T&x,T&y);voidSwap(int&x,int&y);intmain(){inti=9,j=6;doublea=8.3,b=7.8;chars='4',t='5';Swap(i,j);Swap(a,b);Swap(s,t);return0;}template<typename
T>voidSwap(T&x,T&y){Ttemp;temp=x;x=y;y=temp;cout<<"Calloftemplate\n";}voidSwap(int&x,int&y){inttemp;temp=x;x=y;y=x;cout<<"Calloffunction\n";}Result:CalloffunctionCalloftemplateCalloftemplateWhenanon-templatefunctionprovidesanequallygoodmatchforacallasafunctiontemplate,thenon-templateversionispreferred.FunctionTemplates
OverloadingTemplate<typenameT>TgetMin(Tp1,Tp2);TgetMin(Tp1,Tp2,Tp3);Template<typenameT>TgetMin(Tp1,Tp2);intgetMin(intp1,intp2);Wecandeclareseveralfunctiontemplateswiththesamenameandevendeclareacombinationoffunctiontemplatesandordinaryfunctionswiththesamename.Thecompileralwaysmatchesfirstfunctionprototypes(exactlymatching),andthenfunctiontemplates.FunctionTemplates
Overloadingtemplate<typenameT>TgetMax(Tx,Ty){cout<<"callingtemplate\n";return(x>y)?x:y;}intgetMax(inti,intj){cout<<"callingafunctionwithinttype\n";return(i>j)?i:j;}intgetMax(doubled,inti){cout<<"callingafunctionwithadoubletype\n";return(d>i)?(int)d:i;}constintn=7;intmain(){inti=5,j=6;doublea=8.3,b=7.8;charc1='a',c2='b';cout<<getMax(i,j)<<endl;cout<<getMax(c1,c2)<<endl;cout<<getMax(a,b)<<endl;cout<<getMax(n,i)<<endl;cout<<getMax('a',1)<<endl;cout<<getMax(2.7,4)<<endl;return0;}123112232FunctionTemplatesResult:callingafunctionwithinttype6callingtemplatebcallingtemplate8.3callingafunctionwithinttype7callingafunctionwithinttype97callingafunctionwithadoubletype404ClassTemplatesClassTemplatesStackisakindofdatastructurewithLIFO(lastin,firstout).Ithastwoprincipaloperations:pushandpop.CasestudyStack+Stack()+~Stack()-IsEmpty():bool-IsFull():bool+push(int&):void+pop():int+peak():int+getSize():intconst-element:int*size:intconst-top:intClassTemplatesclass
Stack{public:Stack();~Stack();voidpush(int&i);intpop();
intpeak();intgetSize()const;private:boolIsEmpty();boolIsFull();const
intsize;int*element;inttop;};Stack+Stack()+~Stack()-IsEmpty():bool-IsFull():bool+push(int&):void+pop():int+peak():int+getSize():intconst-element:int*size:intconst-top:intStack::Stack():size(5),top(0){element=new
int[size];}Stack::~Stack(){delete[]element;}bool
Stack::IsEmpty(){return--top==-1;}bool
Stack::IsFull(){returntop>=size?true:false;}void
Stack::push(int&i){if(!IsFull())element[top++]=i;elsethrow-1;}int
Stack::pop(){if(IsEmpty())throw-2;returnelement[top];}int
Stack::peak(){returnelement[top-1];}int
Stack::getSize()const{returntop;}ClassTemplatesintmain(){Stackst;try{for(inti=0;i<4;i++)st.push(i);cout<<
"----------------\n";cout<<st.getSize()<<st.peak()<<endl;intnum=st.getSize()+1;for(inti=0;i<num;i++)cout<<st.pop()<<
"";}catch(inte){if(e==-1)cout<<
"Thestackisfull.\n";if(e==-2)cout<<
"Thestackisempty.\n";}}template<typename
T>class
Stack{public:Stack();~Stack();voidpush(T&i);Tpop();Tpeak();intgetSize()const;private:boolIsEmpty();boolIsFull();const
intsize;T*element;inttop;};Definitionof
aClassTemplatetemplate<classT>Tisagenerictype(typeparameter)Defineaclassasatemplate.Thisclassiscalledclasstemplate.Typeparameterintheclassmaybedatamembers,andmemberfunctions’parameters,andreturningvalueClassTemplatetemplate<typename
T>Stack<T>::Stack():size(5),top(0){element=new
T[size];}template<typename
T>Stack<T>::~Stack(){delete[]element;}template<typename
T>bool
Stack<T>::IsEmpty(){return--top==-1;}template<typename
T>bool
Stack<T>::IsFull(){returntop<size?true:false;}template<typename
T>void
Stack<T>::push(T&i){if(IsFull())element[top++]=i;elsethrow-1;}template<typename
T>T
Stack<T>::pop(){if(IsEmpty())throw-2;returnelement[top];}template<typename
T>T
Stack<T>::peak(){returnelement[top-1];}template<typename
T>int
Stack<T>::getSize()const{returntop;}05ClassTemplateInstantiationClassTemplateInstantiationintmain(){Stack<int>st;try{for(inti=0;i<4;i++)st.push(i);cout<<
"----------------\n";cout<<st.getSize()<<st.peak()<<endl;intnum=st.getSize()+1;for(inti=0;i<num;i++)cout<<st.pop()<<
"";}catch(inte){if(e==-1)cout<<
"Thestackisfull.\n";if(e==-2)cout<<
"Thestackisempty.\n";}}Classtemplateisinstantiated.st
isatemplateclassobjectTheprocessofgeneratingaconcreteclassfromatemplatedefinitionandtemplateargumentsisoftencalledclass
templateinstantiation.ClassTemplateInstantiationclass
A{public:A()=default;A(int
x):a(x){}friend
ostream&operator<<(ostream&o,A&obj){o<<obj.a;
returno;}private:inta;};intmain(){Stack<A>stObj;try{cout<<
"objectsarepushedintoastackonebyone.\n";for(inti=0;i<4;i++){Aobj=A(i);stObj
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 二零二四年工业用地买卖合同
- 2025年度绿色能源储煤场建设与运营管理合作协议3篇
- 二零二四年广告发布合同标的及发布内容
- 二零二五年度房地产项目合作开发合同6篇
- 2024销售云服务超兔一体云CRM系统实施合同3篇
- 2025年园林景观草籽草坪种植与维护合同3篇
- 2025年度房地产项目融资财产保全及监管合同3篇
- 2025年度高速公路绿化带建设及养护服务合同4篇
- 二零二五版房地产营销推广甲乙战略合作合同
- 现代文学史自考知识点:曹禺作品考点总结
- 鸡鸭屠宰生产企业安全风险分级管控资料
- 高中物理必修一第六节共点力的平衡条件及其应用课件
- 2020版曼昆版宏观经济学(第十版)课件第3章
- 医院感染管理组织架构图
- 《工程招投标与合同管理》题库试题及答案 共5套试卷
- 离子色谱法分析氯化物原始记录 (1)
- 高等数学说课稿PPT课件(PPT 49页)
- 造影剂肾病概述和性质
- 单片机交通灯系统设计报告
- 标杆房企人力资源体系研究之龙湖
- 招商部人员绩效考核办法最全方案
评论
0/150
提交评论