C++計(jì)算機(jī)語言教學(xué)課件Lect10_第1頁
C++計(jì)算機(jī)語言教學(xué)課件Lect10_第2頁
C++計(jì)算機(jī)語言教學(xué)課件Lect10_第3頁
C++計(jì)算機(jī)語言教學(xué)課件Lect10_第4頁
C++計(jì)算機(jī)語言教學(xué)課件Lect10_第5頁
已閱讀5頁,還剩36頁未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡介

C++計(jì)算機(jī)語言教學(xué)課件Lect10ObjectivesInthischapter,youwilllearn:Tobeabletouseclasstemplatestocreateagroupofrelatedtypes.Tobeabletodistinguishbetweenfunctiontemplatesandtemplatefunctions,aswellasbetweenclasstemplatesandtemplateclasses.Tounderstandhowtooverloadtemplatefunctions.Tounderstandtherelationshipsamongtemplates,friends,inheritanceandstaticmembers.對不同類型的數(shù)組,實(shí)現(xiàn)自加算法1.不使用函數(shù)模板voidselfAdd(intarray[],intval,intsize){

for(inti=0;i<size;i++) array[i]+=val;}voidselfAdd(floatarray[],floatval,intsize){

for(inti=0;i<size;i++) array[i]+=val;}voidselfAdd(doublearray[],doubleval,intsize){

for(inti=0;i<size;i++) array[i]+=val;}9.1 Introduction實(shí)現(xiàn)代碼相同,支持?jǐn)?shù)據(jù)類型不同9.1 Introduction對不同類型的數(shù)組,實(shí)現(xiàn)自加算法2. 使用函數(shù)模板Template<class

T>voidselfAdd(T

array[],Tval,intsize){

for(inti=0;i<size;i++) array[i]+=val;}9.1 IntroductionTemplatesEasilycreatealargerangeofrelatedfunctionsorclasses

將一段程序所處理的對象的數(shù)據(jù)類型參數(shù)化,以使得這段程序可以用于處理多種不同數(shù)據(jù)類型的對象。這避免了功能相同,數(shù)據(jù)類型不同的類出現(xiàn),實(shí)現(xiàn)代碼復(fù)用。

將一個(gè)類所需要的數(shù)據(jù)類型參數(shù)化,使得該類成為能處理多種數(shù)據(jù)類型的通用類。在類的對象被創(chuàng)建時(shí),通過指定參數(shù)所屬的數(shù)據(jù)類型,來將通用類實(shí)例化。這里的數(shù)據(jù)類型包括: 1.數(shù)據(jù)成員的類型2.成員函數(shù)的參數(shù)的類型

3.函數(shù)返回值的類型9.1 IntroductionTemplatesEasilycreatealargerangeofrelatedfunctionsorclasses

將一段程序所處理的對象的數(shù)據(jù)類型參數(shù)化,以使得這段程序可以用于處理多種不同數(shù)據(jù)類型的對象。這避免了功能相同,數(shù)據(jù)類型不同的類出現(xiàn),實(shí)現(xiàn)代碼復(fù)用。在templatedeclarations(模板聲明)中對模板類型參數(shù)定義時(shí),"class"和"typename"是相同的。

template<classT>classWidget;//uses"class"

template<typenameT>classWidget;//uses"typename"9.1 IntroductionFunctiontemplate-theblueprintoftherelatedfunctions

函數(shù)模板提供了一類函數(shù)的抽象,即代表一類函數(shù)。函數(shù)模板實(shí)例化后生成具體的模板函數(shù)。Templatefunction-aspecificfunctionmadefromafunctiontemplate

模板函數(shù)是具體的函數(shù)。

一般來說,模板函數(shù)在需要的時(shí)候才會(huì)生成。如 template<classT> Tadd(Ta,Tb)

在沒有使用此函數(shù)模板的時(shí)候,并不會(huì)實(shí)例化任何函數(shù)模板,當(dāng)調(diào)用add(1,2)的時(shí)候,會(huì)生成模板函數(shù)intadd(inta,intb),當(dāng)調(diào)用add(1.2,1.4)的時(shí)候,才會(huì)生成模板函數(shù)doubleadd(doublea,douleb)類和對象、函數(shù)模板和模板函數(shù)、類模板和模板類之間的關(guān)系。類對象函數(shù)模板(一類函數(shù))模板函數(shù)(具體的函數(shù))實(shí)例化生成實(shí)例化生成類模板(類型參數(shù)化)模板類(具體的類)實(shí)例化生成9.1 IntroductionFunctiontemplates

普通函數(shù)和類的成員函數(shù)可以聲明為函數(shù)模板。Format:

template<classortypenameT>

returnType

functionName(parameterList){//definition}Example:

Template<class

T> voidselfAdd(T

array[],Tval,intsize){

for(inti=0;i<size;i++) array[i]+=val; }

9.1 Introduction9.1 Introduction模板函數(shù)的參數(shù)分為:函數(shù)實(shí)參和模板實(shí)參。 Template<class

T> voidselfAdd(T

array[],Tval,intsize){…}

intmain(){ inta[10],val=2; seftAdd(a,val,10);//省略模板實(shí)參 seftAdd<int>(a,val,10);

return0; }模板實(shí)參函數(shù)實(shí)參模板函數(shù)的模板實(shí)參在下列情況下,不能省略。1.從函數(shù)實(shí)參獲得的信息有矛盾2.需要獲得特定類型的返回值3.虛擬類型參數(shù)沒有出現(xiàn)在模板函數(shù)的形參表中4.函數(shù)模板含有常規(guī)形參9.1 Introduction1.從函數(shù)實(shí)參獲得的信息有矛盾:template<typenameT>Tadd(Ta,Tb){returna+b;}而調(diào)用語句為:cout<<add(3.0,5)<<endl;//error:歧義產(chǎn)生cout<<add<float>(3.0,5)<<endl;//OK!9.1 Introduction2.需要獲得特定類型的返回值:

例如,需要add返回一個(gè)int型的值,

直接調(diào)用add<int>(a,b);9.1 Introduction9.1 Introduction3.虛擬類型參數(shù)沒有出現(xiàn)在模板函數(shù)的形參表中(多義性)。如下圖所示,為避免T2的數(shù)據(jù)類型未知,必須指定T2的數(shù)據(jù)類型。。template<typenameT1,typenameT2,typenameT3>T2add(T1a,T3b){returna+b;}voidmain(){ cout<<showpoint; cout<<add<double,int>(3,5L)<<endl; cout<<add<int,double,long>(3,5L)<<endl;}程序運(yùn)行結(jié)果為:88.00000當(dāng)函數(shù)模板含有常規(guī)形參時(shí),如果常規(guī)參數(shù)的信息無法從模板函數(shù)的實(shí)參表中獲得,則在調(diào)用時(shí)必須顯式的給出對應(yīng)于常規(guī)參數(shù)的模板實(shí)參。9.1 Introductiontemplate<classT,introws>sum(Tdata[],T&result){result=0;

for(inti=0;i<rows;i++) result+=data[i];}intmain(){intd[3]={1,2,3};intr;

sum<int,3>(d,r);//此處必須顯式給出對應(yīng)于常規(guī)參數(shù)的模板實(shí)參9.2 ClassTemplatesClasstemplatesAllowtype-specificversionsofgenericclassesFormat:

template<classT>

class

ClassName{definition};Neednotuse"T",anyidentifierwillworkTocreateanobjectoftheclass,typeClassName<type>myObject;Example:Stack<double>doubleStack;9.2 ClassTemplates(II) FunctionTemplateinclassDefinednormally,butprecededbytemplate<classT>GenericdatainclasslistedastypeTBinaryscoperesolutionoperatorused MyClass<T>::MyClass(intsize)Functiontemplateinclassdefinition://Constructordefinition-createsanarrayoftypeTtemplate<classT>MyClass<T>::MyClass(intsize){ myArray=newT[size];}形參的名字不能在模板內(nèi)部重用,也就是說一個(gè)名字在一個(gè)模板中只能使用一次:

template<classu,classu>//error模板的聲明和定義中參數(shù)的名字可以不同:

聲明:template<classU> classA定義:template<classT>

classA{}。9.2 ClassTemplates(III) tstack1.h(Part1of3)tstack1.h(Part2of3)tstack1.h(Part3of3)fig22_01.cpp(Part1of3)fig22_01.cpp(Part2of3)fig22_01.cpp(Part3of3)ProgramOutputPushingelementsontodoubleStack1.12.23.34.45.5Stackisfull.Cannotpush6.6

PoppingelementsfromdoubleStack5.54.43.32.21.1Stackisempty.Cannotpop

PushingelementsontointStack12345678910Stackisfull.Cannotpush11

PoppingelementsfromintStack10987654321Stackisempty.Cannotpopfig22_02.cpp(Part1of2)fig22_02.cpp(Part2of2)ProgramOutputPushingelementsontodoubleStack1.12.23.34.45.5Stackisfull.Cannotpush6.6

PoppingelementsfromdoubleStack5.54.43.32.21.1Stackisempty.Cannotpop

PushingelementsontointStack12345678910Stackisfull.Cannotpush11

PoppingelementsfromintStack10987654321Stackisempty.Cannotpop9.3 ClassTemplatesandNon-typeParametersCanusenon-typeparametersintemplatesDefaultargument非類型參數(shù)?

可以是常整數(shù)(包括枚舉)、指向外部鏈接對象的指針,而浮點(diǎn)數(shù),指向內(nèi)部鏈接對象的指針則不行。(內(nèi)部鏈接對象和外部鏈接對象的定義與本節(jié)課內(nèi)容無關(guān),將在實(shí)驗(yàn)課上說明)Example:Template<classT,intelements>Stack<double,100>mostRecentSalesFigures;

Definesobjectoftype

Stack<double,100>TreatedasconstExample:Thismayappearintheclassdefinition:TstackHolder[elements];//arraytohold

stackCreatesarrayatcompiletime,ratherthandynamicallocationatexecutiontime9.3 ClassTemplatesandNon-typeParameters9.3 ClassTemplatesandClassTemplateSpecializationClassescanbeoverridden重寫FortemplateclassArray,defineaclassnamedArray<myCreatedType>Thisnewclassoverridestheclasstemplatefor

myCreatedTypeThetemplateremainsforunoverridentypes應(yīng)用場景:即想使用模板,同時(shí)又需要對一個(gè)特殊類型做不同的實(shí)現(xiàn)。9.3 ClassTemplatesandClassTemplateSpecialization//classtemplate:template<classT>classspecTemplate{Tm_var;public:specTemplate(TinData){m_var=inData;}Tincrease(){return++m_var;}};//classtemplatespecialization:template<>classspecTemplate<char>{

charm_var;public:specTemplate(chararg){m_var=arg;}

charupperCase(){if((m_var>=’a’)&&(m_var<=’z’))m_var+=’A’-’a’;

returnm_var;}};9.4 TemplatesandInheritanceAnon-templateclasscanbederivedfromatemplateclass(普通類繼承模板類)Atemplateclasscanbederivedfromanon-templateclass(模板類繼承了普通類(非常常見))Aclasstemplatecanbederivedfromaclasstemplate(類模板繼承類模板)Atemplateclasscanbederivedfromaclasstemplate(模板類繼承類模板,即繼承模板參數(shù)給出的基類)1.普通類繼承模板類9.4 TemplatesandInheritancetemplate<classT>classTBase{ Tdata;……};classDerived:publicTBase<int>{……};2.類模板繼承了普通類(非常常見)9.4 TemplatesandInheritanceclassTBase{……};template<classT>classTDerived:publicTBase{Tdata;……};9.4 TemplatesandInheritance3.類模板繼承類模板template<classT>classTBase{Tdata1;……};template<classT1,classT2>classTDerived:publicTBase<T1>{T2data2;……};9.4 TemplatesandInheritance4.模板類繼承模板參數(shù)給出的基類——繼承哪個(gè)基類由模板參數(shù)決定9.4 TemplatesandInheritance4.模板類繼承模板參數(shù)給出的基類——繼承哪個(gè)基類由模板參數(shù)決定#include<iostream>usingnamespacestd;classBaseA{public: BaseA(){cout<<"BaseAfouned"<<endl;}};classBaseB{public: BaseB(){cout<<"BaseBfouned"<<endl;}};9.4 TemplatesandInheritance4.模板類繼承模板參數(shù)給出的基類——繼承哪個(gè)基類由模板參數(shù)決定#include<iostream>usingnamespacestd;classBaseA{public: BaseA(){cout<<"BaseAfouned"<<endl;}};classBaseB{public: BaseB(){cout<<"BaseBfouned"<<endl;}};template<typenameT>classBaseC{private: Tdata;public: BaseC(Tn):data(n){ cout<<"BaseCfouned"<<data<<endl;}};template<classT>classDerived:publicT{public: Derived():T(){cout<<"Derivedfouned"<<endl;}};9.4 TemplatesandInheritance4.模板類繼承模板參數(shù)給出的基類——繼承哪個(gè)基類由模板參數(shù)決定#include<iostream>usingnamespacestd;classBaseA{public: BaseA(){cout<<"BaseAfouned"<<endl;}};classBaseB{public: BaseB(){cout<<"BaseBfouned"<<endl;}};template<typenameT>classBaseC{private: Tdata;public: BaseC(Tn):data(n){ cout<<"BaseCfouned"<<data<<endl;}};template<classT>classDerived:publicT{public: Derived():T(){cout<<"Derivedfouned"<<endl;}};voidmain(){

Derived<BaseA>x;//BaseA作為基類

Derived<BaseB>y;//BaseB作為基類

Derived<BaseC<int>>z;//BaseC<int,3>作為基類}程序運(yùn)行結(jié)果為:BaseAfounedDerivedfounedBaseBfounedDerivedfounedBaseCfouned3Derivedfouned9.5 TemplatesandfriendsFriendshipsallowedbetweenaclasstemplateandGlobalfunction全局函數(shù)Memberfunctionofanotherclass別的類的成員函數(shù)Entireclass友元類friendfunctionsInsidedefinitionofclasstemp

溫馨提示

  • 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

提交評論