![C++計算機語言教學(xué)課件Lect10_第1頁](http://file4.renrendoc.com/view/681cbe35751979cd4720fcfa805e3422/681cbe35751979cd4720fcfa805e34221.gif)
![C++計算機語言教學(xué)課件Lect10_第2頁](http://file4.renrendoc.com/view/681cbe35751979cd4720fcfa805e3422/681cbe35751979cd4720fcfa805e34222.gif)
![C++計算機語言教學(xué)課件Lect10_第3頁](http://file4.renrendoc.com/view/681cbe35751979cd4720fcfa805e3422/681cbe35751979cd4720fcfa805e34223.gif)
![C++計算機語言教學(xué)課件Lect10_第4頁](http://file4.renrendoc.com/view/681cbe35751979cd4720fcfa805e3422/681cbe35751979cd4720fcfa805e34224.gif)
![C++計算機語言教學(xué)課件Lect10_第5頁](http://file4.renrendoc.com/view/681cbe35751979cd4720fcfa805e3422/681cbe35751979cd4720fcfa805e34225.gif)
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)
文檔簡介
C++計算機語言教學(xué)課件Lect10ObjectivesInthischapter,youwilllearn:Tobeabletouseclasstemplatestocreateagroupofrelatedtypes.Tobeabletodistinguishbetweenfunctiontemplatesandtemplatefunctions,aswellasbetweenclasstemplatesandtemplateclasses.Tounderstandhowtooverloadtemplatefunctions.Tounderstandtherelationshipsamongtemplates,friends,inheritanceandstaticmembers.對不同類型的數(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實現(xiàn)代碼相同,支持?jǐn)?shù)據(jù)類型不同9.1 Introduction對不同類型的數(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),實現(xiàn)代碼復(fù)用。
將一個類所需要的數(shù)據(jù)類型參數(shù)化,使得該類成為能處理多種數(shù)據(jù)類型的通用類。在類的對象被創(chuàng)建時,通過指定參數(shù)所屬的數(shù)據(jù)類型,來將通用類實例化。這里的數(shù)據(jù)類型包括: 1.數(shù)據(jù)成員的類型2.成員函數(shù)的參數(shù)的類型
3.函數(shù)返回值的類型9.1 IntroductionTemplatesEasilycreatealargerangeofrelatedfunctionsorclasses
將一段程序所處理的對象的數(shù)據(jù)類型參數(shù)化,以使得這段程序可以用于處理多種不同數(shù)據(jù)類型的對象。這避免了功能相同,數(shù)據(jù)類型不同的類出現(xiàn),實現(xiàn)代碼復(fù)用。在templatedeclarations(模板聲明)中對模板類型參數(shù)定義時,"class"和"typename"是相同的。
template<classT>classWidget;//uses"class"
template<typenameT>classWidget;//uses"typename"9.1 IntroductionFunctiontemplate-theblueprintoftherelatedfunctions
函數(shù)模板提供了一類函數(shù)的抽象,即代表一類函數(shù)。函數(shù)模板實例化后生成具體的模板函數(shù)。Templatefunction-aspecificfunctionmadefromafunctiontemplate
模板函數(shù)是具體的函數(shù)。
一般來說,模板函數(shù)在需要的時候才會生成。如 template<classT> Tadd(Ta,Tb)
在沒有使用此函數(shù)模板的時候,并不會實例化任何函數(shù)模板,當(dāng)調(diào)用add(1,2)的時候,會生成模板函數(shù)intadd(inta,intb),當(dāng)調(diào)用add(1.2,1.4)的時候,才會生成模板函數(shù)doubleadd(doublea,douleb)類和對象、函數(shù)模板和模板函數(shù)、類模板和模板類之間的關(guān)系。類對象函數(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ù)實參和模板實參。 Template<class
T> voidselfAdd(T
array[],Tval,intsize){…}
intmain(){ inta[10],val=2; seftAdd(a,val,10);//省略模板實參 seftAdd<int>(a,val,10);
return0; }模板實參函數(shù)實參模板函數(shù)的模板實參在下列情況下,不能省略。1.從函數(shù)實參獲得的信息有矛盾2.需要獲得特定類型的返回值3.虛擬類型參數(shù)沒有出現(xiàn)在模板函數(shù)的形參表中4.函數(shù)模板含有常規(guī)形參9.1 Introduction1.從函數(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返回一個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;}程序運行結(jié)果為:88.00000當(dāng)函數(shù)模板含有常規(guī)形參時,如果常規(guī)參數(shù)的信息無法從模板函數(shù)的實參表中獲得,則在調(diào)用時必須顯式的給出對應(yīng)于常規(guī)參數(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ù)的模板實參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)部重用,也就是說一個名字在一個模板中只能使用一次:
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ù)(包括枚舉)、指向外部鏈接對象的指針,而浮點數(shù),指向內(nèi)部鏈接對象的指針則不行。(內(nèi)部鏈接對象和外部鏈接對象的定義與本節(jié)課內(nèi)容無關(guā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)用場景:即想使用模板,同時又需要對一個特殊類型做不同的實現(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ù)給出的基類——繼承哪個基類由模板參數(shù)決定9.4 TemplatesandInheritance4.模板類繼承模板參數(shù)給出的基類——繼承哪個基類由模板參數(shù)決定#include<iostream>usingnamespacestd;classBaseA{public: BaseA(){cout<<"BaseAfouned"<<endl;}};classBaseB{public: BaseB(){cout<<"BaseBfouned"<<endl;}};9.4 TemplatesandInheritance4.模板類繼承模板參數(shù)給出的基類——繼承哪個基類由模板參數(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ù)給出的基類——繼承哪個基類由模板參數(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>作為基類}程序運行結(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)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 現(xiàn)代科技助力白水泥行業(yè)財務(wù)風(fēng)險管理
- 衛(wèi)浴潔具國慶節(jié)活動方案
- 環(huán)境藝術(shù)設(shè)計與室內(nèi)設(shè)計的審美互動
- 生產(chǎn)工藝流程中的質(zhì)量控制與安全管理
- 現(xiàn)代服務(wù)業(yè)在商業(yè)地產(chǎn)中的價值挖掘
- 物流技術(shù)與管理教育的新模式
- Unit 4 Plants around us Lesson 6(說課稿)-2024-2025學(xué)年人教PEP版(2024)英語三年級上冊
- 7《可愛的動物》(說課稿)2023-2024學(xué)年統(tǒng)編版道德與法治一年級下冊
- Unit 2 Whats your name (Story time)(說課稿)-2024-2025學(xué)年譯林版(三起)(2024)英語三年級上冊001
- Unit 4 A glimpse of the future 說課稿-2023-2024學(xué)年高二下學(xué)期英語外研版(2019)選擇性必修第三冊001
- 公共組織學(xué)(第三版)課件:公共組織結(jié)構(gòu)
- 人教版八年級上冊地理2024-2025學(xué)年八年級上冊地理第一章 從世界看中國 測試卷(一)(含答案)
- 2024年中國工業(yè)涂料行業(yè)發(fā)展現(xiàn)狀、市場前景、投資方向分析報告(智研咨詢發(fā)布)
- 化工企業(yè)重大事故隱患判定標(biāo)準(zhǔn)培訓(xùn)考試卷(后附答案)
- 工傷賠償授權(quán)委托書范例
- 食堂餐具炊具供貨服務(wù)方案
- 員工安全健康手冊
- 自然科學(xué)基礎(chǔ)(小學(xué)教育專業(yè))全套教學(xué)課件
- 華為客服制度
- 醫(yī)美面部抗衰老注射項目培訓(xùn)課件
- 小學(xué)語文閱讀教學(xué)落實學(xué)生核心素養(yǎng)方法的研究-中期報告
評論
0/150
提交評論