Download presentation
Presentation is loading. Please wait.
1
CS 202 Computer Science II Lab Fall 2009 October 22
2
Today Topics Templates
3
Why Templates? One of the C++ Powerful Features One for All – Function Template : a code segment for a set of related functions – Class Template : a code segment for a set of related classes
4
Syntax ! template declarations; template: reserved word class: refer to any user-defined type or built-in type Type: refer to formal parameter to the template
5
Function Templates ! template function definition; template Type larger(Type x, Type y) { if (x>=y) return x; else return y; }
6
Class Templates ! template class declaration;
7
Class Templates Example! template class templateMath { public: type1 add (type1, type1); type1 mul (type1, type1); }; template type1 templateMath ::add (type1 a, type1 b) { return a+b; } template type1 templateMath ::mul(type1 a, type1 b) { return a*b; }
8
Class Templates Example! templateMath tM;
9
Class Templates Example! template type1 templateMath ::myPow (type1 a, int b) { return pow(a, b); }
10
Class Templates Example! template class templateMath { private: type1 myArray[input]; public: type1 add (type1, type1); type1 mul (type1, type1); type1 myPow (type1, int); void setMember(type1, int); type1 getMember(int); };
11
Class Templates Example! template type1 templateMath ::add (type1 a, type1 b) { return a+b; }
12
Class Templates Example! template void templateMath ::setMember(type1 a, int b) { if(b<0 || input<=b) return; myArray[b] = a; } template type1 templateMath ::getMember(int b) { if(b<0 || input<=b) return 0; return myArray[b]; }
13
Class Templates Example! templateMath tM;
14
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.