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

下載本文檔

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

文檔簡介

1、Chapter 9 - C+ TemplatesOutline9.1Introduction9.2Class Templates9.3Class Templates and Non-type Parameters9.4Templates and Inheritance9.5Templates and friends9.6Templates and static Members 9.7 Specific class TemplateObjectives In this chapter, you will learn: To be able to use class templates to cr

2、eate a group of related types. To be able to distinguish between function templates and template functions, as well as between class templates and template classes. To understand how to overload template functions. To understand the relationships among templates, friends, inheritance and static memb

3、ers.對不同類型的數(shù)組,實(shí)現(xiàn)自加算對不同類型的數(shù)組,實(shí)現(xiàn)自加算法法1. 不使用函數(shù)模板不使用函數(shù)模板void selfAdd( int array, int val, int size ) for ( int i = 0; i size; i+ )arrayi += val ; void selfAdd( float array, float val, int size ) for ( int i = 0; i size; i+ )arrayi += val ; void selfAdd( double array, double val, int size ) for ( int i =

4、0; i size; i+ )arrayi += val ; 9.1Introduction實(shí)現(xiàn)代碼相同,支持?jǐn)?shù)據(jù)類型不同9.1 Introduction對不同類型的數(shù)組,實(shí)現(xiàn)自加算法對不同類型的數(shù)組,實(shí)現(xiàn)自加算法2. 使用函數(shù)模板使用函數(shù)模板Template void selfAdd( T array, T val, int size ) for ( int i = 0; i size; i+ )arrayi += val ; 9.1Introduction Templates Easily create a large range of related functions or class

5、es將一段程序所處理的對象的數(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.1Introduction Templates Easily create a large range of related functions or classes將一段程序所處理的對象的數(shù)據(jù)類型參數(shù)化,以使得這段

6、程序可以用于處理多種不同數(shù)據(jù)類型的對象。這避免了功能相同,數(shù)據(jù)類型不同的類出現(xiàn), 實(shí)現(xiàn)代碼復(fù)用。在template declarations(模板聲明)中對模板類型參數(shù)定義時(shí), class 和 typename是相同的。template class Widget; / uses classtemplate class Widget; / uses typename9.1 Introduction Function template - the blueprint of the related functions函數(shù)模板提供了一類函數(shù)的抽象,即代表一類函數(shù)。函數(shù)模板實(shí)例化后生成具體的模板函數(shù)。

7、Template function - a specific function made from a function template模板函數(shù)是具體的函數(shù)。一般來說,模板函數(shù)在需要的時(shí)候才會生成。如templateT add(T a, T b)在沒有使用此函數(shù)模板的時(shí)候,并不會實(shí)例化任何函數(shù)模板,當(dāng)調(diào)用add(1, 2)的時(shí)候,會生成模板函數(shù)int add(int a, int b),當(dāng)調(diào)用add(1.2, 1.4)的時(shí)候,才會生成模板函數(shù)double add(double a, doule b) 類和對象、函數(shù)模板和模板函數(shù)、類模板和模板類之間的關(guān)系。類對象函數(shù)模板(一類函數(shù))模板函數(shù)(

8、具體的函數(shù))實(shí)例化生成實(shí)例化生成類模板(類型參數(shù)化)模板類(具體的類)實(shí)例化生成9.1 Introduction Function templates 普通函數(shù)普通函數(shù)和類的成員函數(shù)類的成員函數(shù)可以聲明為函數(shù)模板。 Format:template returnType functionName( parameterList )/definition Example:Example:Template void selfAdd( T array, T val, int size ) for ( int i = 0; i size; i+ )arrayi += val ; 9.1 Introduct

9、ion9.1 Introduction 模板函數(shù)的參數(shù)分為:函數(shù)實(shí)參函數(shù)實(shí)參和模板實(shí)參模板實(shí)參。Template void selfAdd( T array, T val, int size ) int main() int a10, val = 2 ;seftAdd( a, val, 10 ) ; /省略模板實(shí)參seftAdd( a, val, 10 ) ; return 0 ;模板實(shí)參函數(shù)實(shí)參 模板函數(shù)的模板實(shí)參在下列情況下,不能省略。 1. 從函數(shù)實(shí)參獲得的信息有矛盾 2. 需要獲得特定類型的返回值 3. 虛擬類型參數(shù)沒有出現(xiàn)在模板函數(shù)的形參表中 4. 函數(shù)模板含有常規(guī)形參9.1 Int

10、roduction1. 從函數(shù)實(shí)參獲得的信息有矛盾:templateT add(T a,T b)return a+b;而調(diào)用語句為:cout add( 3.0, 5 ) endl ; /error:歧義產(chǎn)生cout add( 3.0, 5 ) endl ; /OK!9.1 Introduction2. 需要獲得特定類型的返回值:例如,需要add返回一個(gè) int 型的值,直接調(diào)用add( a, b ) ;9.1 Introduction9.1 Introduction3. 虛擬類型參數(shù)沒有出現(xiàn)在模板函數(shù)的形參表中(多義性)。如下圖所示,為避免T2的數(shù)據(jù)類型未知,必須指定T2的數(shù)據(jù)類型。templ

11、ateT2 add(T1 a,T3 b)return a+b;void main() coutshowpoint;coutadd(3,5L)endl;coutadd(3,5L)endl;程序運(yùn)行結(jié)果為:程序運(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 sum(T data,T &result)result=0; for(int i=0;irows;i+)result+=datai;int main()int d3=1,2,3;in

12、t r; sum(d,r); /此處必須顯式給出對應(yīng)于常規(guī)參數(shù)的模板實(shí)參此處必須顯式給出對應(yīng)于常規(guī)參數(shù)的模板實(shí)參9.2Class Templates Class templates Allow type-specific versions of generic classes Format:template class ClassNamedefinition ; ; Need not use T, any identifier will work To create an object of the class, typeClassName ClassName myObject;Example

13、: Stack doubleStack;9.2Class Templates (II) Function Template in class Defined normally, but preceded by template Generic data in class listed as type T Binary scope resolution operator usedMyClass:MyClass(int size) Function template in class definition:/Constructor definition - creates an array of

14、type TtemplateMyClass:MyClass(int size) myArray = new Tsize; 形參的名字不能在模板內(nèi)部重用,也就是說一個(gè)名字在一個(gè)模板中只能使用一次:template /error 模板的聲明和定義中參數(shù)的名字可以不同:聲明:template class A定義:template class A。9.2Class Templates (III)Outlinetstack1.h (Part 1 of 3)Outlinetstack1.h (Part 2 of 3)Outlinetstack1.h (Part 3 of 3)fig22_01.cpp (P

15、art 1 of 3)Outlinefig22_01.cpp (Part 2 of 3)Outlinefig22_01.cpp (Part 3 of 3)Program OutputPushing elements onto doubleStack1.1 2.2 3.3 4.4 5.5Stack is full. Cannot push 6.6 Popping elements from doubleStack5.5 4.4 3.3 2.2 1.1Stack is empty. Cannot pop Pushing elements onto intStack1 2 3 4 5 6 7 8 9

16、 10Stack is full. Cannot push 11 Popping elements from intStack10 9 8 7 6 5 4 3 2 1Stack is empty. Cannot popOutlinefig22_02.cpp (Part 1 of 2)Outlinefig22_02.cpp (Part 2 of 2)OutlineProgram OutputPushing elements onto doubleStack1.1 2.2 3.3 4.4 5.5Stack is full. Cannot push 6.6 Popping elements from

17、 doubleStack5.5 4.4 3.3 2.2 1.1Stack is empty. Cannot pop Pushing elements onto intStack1 2 3 4 5 6 7 8 9 10Stack is full. Cannot push 11 Popping elements from intStack10 9 8 7 6 5 4 3 2 1Stack is empty. Cannot pop 9.3Class Templates and Non-type Parameters Can use non-type parameters in templates D

18、efault argument 非類型參數(shù)?非類型參數(shù)?可以是常整數(shù)(包括枚舉)、指向外部鏈接對象的指針,而浮點(diǎn)數(shù),指向內(nèi)部鏈接對象的指針則不行。(內(nèi)部鏈接對象內(nèi)部鏈接對象和外部鏈接對象外部鏈接對象的定義與本節(jié)課內(nèi)容無關(guān),將在實(shí)驗(yàn)課上說明)Example:Template Stack mostRecentSalesFigures; Defines object of type Stack Treated as constconstExample: This may appear in the class definition:T stackHolder elements ; /array to

19、 hold stackCreates array at compile time, rather than dynamic allocation at execution time9.3Class Templates and Non-type Parameters9.3Class Templates and Class Template Specialization Classes can be overridden 重寫 For template class Array, define a class namedArray This new class overrides the class

20、 template for myCreatedType The template remains for unoverriden types 應(yīng)用場景:即想使用模板,同時(shí)又需要對一個(gè)特殊類型做不同的實(shí)現(xiàn)。9.3Class Templates and Class Template Specialization/ class template: template class specTemplate T m_var; public: specTemplate (T inData) m_var = inData; T increase () return +m_var; ; / class temp

21、late specialization: template class specTemplate char m_var; public: specTemplate (char arg) m_var = arg; char upperCase () if (m_var = a) & (m_var = z) m_var += A-a; return m_var; ;9.4Templates and Inheritance A non-template class can be derived from a template class(普通類繼承模板類) A template class

22、can be derived from a non-template class(模板類繼承了普通類(非常常見) A class template can be derived from a class template(類模板繼承類模板) A template class can be derived from a class template(模板類繼承類模板,即繼承模板參數(shù)給出的基類)1. 普通類繼承模板類9.4Templates and Inheritancetemplateclass TBaseT data;class Derived:public TBase;2. 類模板繼承了普通

23、類(非常常見)9.4Templates and Inheritanceclass TBase;templateclass TDerived:public TBaseT data;9.4Templates and Inheritance3. 類模板繼承類模板templateclass TBaseT data1;templateclass TDerived:public TBaseT2 data2;9.4Templates and Inheritance 4. 模板類繼承模板參數(shù)給出的基類繼承哪個(gè)基類由模板參數(shù)決定9.4Templates and Inheritance 4. 模板類繼承模板參數(shù)給

24、出的基類繼承哪個(gè)基類由模板參數(shù)決定#includeusing namespace std;class BaseApublic:BaseA()coutBaseA founedendl;class BaseBpublic:BaseB()coutBaseB founedendl;9.4Templates and Inheritance 4. 模板類繼承模板參數(shù)給出的基類繼承哪個(gè)基類由模板參數(shù)決定#includeusing namespace std;class BaseApublic:BaseA()coutBaseA founedendl;class BaseBpublic:BaseB()coutB

25、aseB founedendl;templateclass BaseCprivate:T data;public:BaseC(T n):data(n)coutBaseC founed dataendl;templateclass Derived:public Tpublic:Derived():T()coutDerived founedendl;9.4Templates and Inheritance 4. 模板類繼承模板參數(shù)給出的基類繼承哪個(gè)基類由模板參數(shù)決定#includeusing namespace std;class BaseApublic:BaseA()coutBaseA foun

26、edendl;class BaseBpublic:BaseB()coutBaseB founedendl;templateclass BaseCprivate:T data;public:BaseC(T n):data(n)coutBaseC founed dataendl;templateclass Derived:public Tpublic:Derived():T()coutDerived founedendl;void main()Derived x;/ BaseA作為基類作為基類Derived y;/ BaseB作為基類作為基類DerivedBaseC z; / BaseC作為基類作

27、為基類程序運(yùn)行結(jié)果為:程序運(yùn)行結(jié)果為:BaseA founedDerived founedBaseB founedDerived founedBaseC founed 3Derived founed9.5Templates and friends Friendships allowed between a class template and Global function 全局函數(shù)全局函數(shù) Member function of another class 別的類的成員函數(shù)別的類的成員函數(shù) Entire class 友元類友元類 friend functions Inside definition of class templa

溫馨提示

  • 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)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論