用C++解決問(wèn)題第十版-第17章范本_第1頁(yè)
用C++解決問(wèn)題第十版-第17章范本_第2頁(yè)
用C++解決問(wèn)題第十版-第17章范本_第3頁(yè)
用C++解決問(wèn)題第十版-第17章范本_第4頁(yè)
用C++解決問(wèn)題第十版-第17章范本_第5頁(yè)
已閱讀5頁(yè),還剩46頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡(jiǎn)介

1、Chapter 17TemplatesOverview17.1 Templates for Algorithm Abstraction 17.2 Templates for Data AbstractionSlide 17- 317.1Templates for Algorithm AbstractionTemplates for Algorithm AbstractionFunction definitions often use application specific adaptations of more general algorithmsFor example: The gener

2、al algorithm used in swapValues could swap variables of any type:void swapValues(typeOfVar& v1, typeOfVar& v2) typeOfVar temp; temp = v1; v1 = v2; v2 = temp; Slide 17- 5swapValues for charHere is a version of swapValues to swap character variables: void swapValues(char& v1, char& v2) char temp; temp

3、 = v1; v1 = v2; v2 = temp; Slide 17- 6A General swapValuesA generalized version of swapValues is shownhere.void swapValues(typeOfVar& v1, typeOfVar& v2) typeOfVar temp; temp = v1; v1 = v2; v2 = temp; This function, if typeOfVar could accept any type, could be used to swap values of any typeSlide 17-

4、 7Templates for FunctionsA C+ function template will allow swapValuesto swap values of two variables of the same typeExample: template void swapValues(T& v1, T& v2) T temp; temp = v1; v1 = v2; v = temp; Slide 17- 8Template prefixType parameterTemplate Detailstemplate is the template prefixTells comp

5、iler that the declaration or definition that follows is a templateTells compiler that T is a type parameterclass means type in this context (typename could replace class but class is usually used)T can be replaced by any type argument(whether the type is a class or not)A template overloads the funct

6、ion name by replacing T with the type used in a function callSlide 17- 9Calling a Template FunctionCalling a function defined with a template is identical to calling a normal functionExample: To call the template version of swapValues char s1, s2; int i1, i2; swapValues(s1, s2); swapValues(i1, i2);T

7、he compiler checks the argument types and generates an appropriate version of swapValuesSlide 17- 10Templates and DeclarationsA function template may also have a separatedeclarationThe template prefix and type parameter are used Depending on your compilerYou may, or may not, be able to separate decl

8、aration and definitions of template functions just as you do with regular functionsTo be safe, place template function definitions in the same file where they are usedwith no declarationA file included with #include is, in most cases, equivalent to being in the same file“This means including the .cp

9、p file or .h file with implementation codeSlide 17- 11The Type Parameter TT is the traditional name for the type parameterAny valid, non-keyword, identifier can be usedVariableType could be used template void swapValues(VariableType& v1, VariableType& v2) VariableType temp; Slide 17- 12Display 17.1T

10、emplates with Multiple ParametersFunction templates may use more than oneparameterExample: templateAll parameters must be used in the template functionSlide 17- 13Algorithm AbstractionUsing a template function we can express moregeneral algorithms in C+Algorithm abstraction means expressing algorith

11、ms in a very general way so we can ignore incidental detailThis allows us to concentrate on the substantive part of the algorithmSlide 17- 14Program Example:A Generic Sorting FunctionThe sort function below uses an algorithm thatdoes not depend on the base type of the array void sort(int a, int numb

12、erUsed) int indexOfNextSmallest; for (int index = 0; index numberUsed -1; index+) indexOfNextSmallest = indexOfSmallest(a, index, numberUsed); swapValues(aindex, aindexOfNextSmallest); The same algorithm could be used to sort an array of any typeSlide 17- 15Generic Sorting:Helping Functionssort uses

13、 two helper functions indexOfSmallest also uses a general algorithm andcould be defined with a template swapValues has already been adapted as a templateAll three functions, defined with templates, aredemonstrated in Slide 17- 16Display 17.2 Display 17.3 (1-2)Templates and OperatorsThe function inde

14、xOfSmallest compares itemsin an array using the operatorIf a template function uses an operator, such as , that operator must be defined for the types being comparedIf a class type has the operator overloaded for the class, then an array of objects of the class could be sorted with function template

15、 sortSlide 17- 17Defining TemplatesWhen defining a template it is a good ideaTo start with an ordinary function that accomplishes the task with one typeIt is often easier to deal with a concrete case rather than the general caseThen debug the ordinary functionNext convert the function to a template

16、by replacing type names with a type parameterSlide 17- 18Inappropriate Types for TemplatesTemplates can be used for any type for which the code in the function makes senseswapValues swaps individual objects of a typeThis code would not work, because the assignmentoperator used in swapValues does not

17、 work with arrays: int a10, b10; swapValues(a, b);Slide 17- 19Section 17.1 ConclusionCan youIdentify a template prefix?Identify a parameter type in a template prefix?Compare and contrast function overloading with the use of templates?What additional complexities are involved when class types are inv

18、olved as parameter types?Slide 17- 2017.2Templates for Data AbstractionTemplates for Data AbstractionClass definitions can also be made more generalwith templatesThe syntax for class templates is basically the same as for function templatestemplate comes before the template definitionType parameter

19、T is used in the class definition just like any other type Type parameter T can represent any typeSlide 17- 22A Class TemplateThe following is a class templateAn object of this class contains a pair of values of type Ttemplate class Pair public: Pair( ); Pair( T firstValue, T secondValue); continued

20、 on next slide Slide 17- 23Template Class Pair (cont.)void setElement(int position, T value); /Precondition: position is 1 or 2 /Postcondition: position indicated is set to value T getElement(int position) const; / Precondition: position is 1 or 2 / Returns value in position indicatedprivate: T firs

21、t; T second;Slide 17- 24Declaring Template Class ObjectsOnce the class template is defined, objects may be declaredDeclarations must indicate what type is to be used for TExample: To declare an object so it can hold a pair of integers: Pair score; or for a pair of characters: Pair seats;Slide 17- 25

22、Using the ObjectsAfter declaration, objects based on a templateclass are used just like any other objectsContinuing the previous example: score.setElement(1,3); score.setElement(2,0); seats.setElement(1, A);Slide 17- 26Defining the Member FunctionsMember functions of a template class are definedthe

23、same way as member functions of ordinaryclassesThe only difference is that the member function definitions are themselves templatesSlide 17- 27Defining a Pair ConstructorThis is a definition of the constructor for classPair that takes two argumentstemplate Pair:Pair(T firstValue, T secondValue) : fi

24、rst(firstValue), second(secondValue) /No body needed due to initialization above The class name includes Slide 17- 28Defining setElement Here is a definition for setElement in the template class Pairvoid Pair:setElement(int position, T value) if (position = = 1) first = value; else if (position = =

25、2) second = value; else Slide 17- 29Template Class Names as ParametersThe name of a template class may be used as the type of a function parameterExample: To create a parameter of type Pair: int addUp(const Pair& thePair); /Returns the sum of two integers in thePairSlide 17- 30Template Functions wit

26、h Template Class ParametersFunction addUp from a previous example canbe made more general as a template function: template T addUp(const Pair& thePair) /Precondition: operator + is defined for T /Returns sum of the two values in thePairSlide 17- 31Program Example:An Array ClassThe example in the fol

27、lowing displays is a class template whose objects are listsThe lists can be lists of any typeThe interface is found in The program is inThe implementation is in Slide 17- 32Display 17.4 (1-2)Display 17.5 Display 17.6 (1-3)Implementation NotesNote that in Display 17.4, the class definition for Generi

28、cList, we put the implementation of the overloaded operator in the header file itselfThis is common for template classes with friend operatorsThis is because is a friend, not a member of the class; as a result, implementation is simpler this waySlide 1- 33Separate implementation of overloaded friend

29、 operatorWe can put the implementation of into the implementation file but there is extra workMake forward declaration with the diamond in the .h fileImplement in the .cpp fileSlide 1- 34Display 17.7 Display 17.8typedef and TemplatesYou specialize a class template by giving a typeargument to the cla

30、ss name such as PairThe specialized name, Pair, is used justlike any class nameYou can define a new class type name with thesame meaning as the specialized name:typedef Class_Name New_Type_Name;For example: typedef Pair PairOfInt; PairOfInt pair1, pair2;Slide 17- 35Section 17.2 ConclusionCan youGive

31、 the definition for the member function getElement for the class template Pair?Give the definition for the constructor with zeroarguments for the template class Pair?Slide 17- 36Chapter 17 - EndSlide 17- 37Display 17.1 Slide 17- 38BackNextDisplay 17.2Slide 17- 39BackNextDisplay 17.3 (1/2)Slide 17- 4

32、0BackNextDisplay 17.3 (2/2)Slide 17- 41BackNextDisplay 17.4 (1/2)Slide 17- 42BackNextDisplay 17.4(2/2)Slide 17- 43BackNextDisplay 17.51/2Slide 17- 44BackNextDisplay 17.52/2Slide 17- 45BackNextDisplay 17.61/3Slide 17- 46BackNext 1/This is the implementation file: genericlist.cpp 2/This is the impleme

33、ntation of the class template named GenericList. 3/The interface for the class template GenericList is in the 4/header file genericlist.h. 5#ifndef GENERICLIST_CPP 6#define GENERICLIST_CPP 7#include 8#include 9#include genericlist.h /This is not needed when used as we are using this file,10 /but the

34、 #ifndef in genericlist.h makes it safe.11using namespace std;1213namespace listsavitch1415 /Uses cstdlib:16 template17 GenericList:GenericList(int max) : maxLength(max),18 currentLength(0)19 20 item = new ItemTypemax;21 Display 17.6 (2/3)Slide 17- 47BackNext2223 template24 GenericList:GenericList(

35、)25 26 delete item;27 2829 template30 int GenericList:length( ) const31 32 return (currentLength);33 3435 /Uses iostream and cstdlib:36 template37 void GenericList:add(ItemType newItem)38 39 if ( full( ) )40 41 cout Error: adding to a full list.n;42 exit(1);43 44 else45 46 itemcurrentLength = newItem;47 currentLength = currentLength + 1;48 49 Display 17.6(3/3)Slide 17- 48BackNext51 template52 bool GenericList:full( ) co

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 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ì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論