Download presentation
Presentation is loading. Please wait.
Published byMartin Webster Modified over 9 years ago
1
C++ Lecture 9 Tuesday, 26 Aug 2005
2
Templates l Template can be a class or function that has data types as parameters. The types are realized when the template is used, where the types are replaced by actual types. The corresponding code is generated by compiler.
3
Overloaded Square Functions l int sq(int i) { return i*i; } l float sq(float f) { return f*f; } l double sq(double d) { return d*d; } l complex sq(complex c) { return c*c; }
4
Template Functions l Using template, all four functions can be coded in one: template T sq(T x) { return x*x;} l Use the template function as l sq(i); sq(f); sq(d); or sq(c); Assuming i is int, f is float, d is double, and c is complex. C.f. sq.cpp
5
General Form of Function Templates template void func(const T *a, S b, …) { (function definition using T & S etc) } l T and S must appear in the parameter list. C.f. Fig.12.2 (old)
6
Class Templates template class Stack { public: … bool pop(T&); private: T *stackPtr; } C.f. Fig.12.3 (old) and tstack1.h
7
Definition of Class Functions with Template template bool Stack ::pop(T &popv) { …. }
8
Use of Templates Stack dstk(100); Stack istk(1000); Stack bstk(500); l The parameter T is instantiated by the actual type in the angular bracket.
9
Non-Type Parameters in Class Templates template class Stack { … sPtr = new T[el]; … } l Stack stk;
10
Standard Template Library l Container classes: vector, list, set, stack, queue etc. l Iterators: pointer-like objects l Generic algorithms: copy, fill, remove, rotate, etc. C.f. Fig 20.14 and Fig.20.15 (old)
11
Error Handing with assert( ) l #include l assert(int_expr); l Program stops and prints the assert( ) code line if int_expr becomes false (I.e. int_expr is 0).
12
Exception Handing try { code that may evoke: throw e; } catch (type e) { exception handing code } e can be a class C.f. Fig.13.1 (old)
13
Typedef l typedef data-type new-name struct Card { int pip; char *suit; }; typedef card* cptr; cptr deck;
14
Bitwise Operations l &bitwise AND l |bitwise OR l ^bitwise exclusive OR l <<left shift l >>right shift l ~one’s complement
15
Bitwise Examples l 00..0110 & 00..1100 -> 00..0100 l 00..0110 | 00..1100 -> 00..1110 l 00..0110 ^ 00..1100 -> 00..1010 l 00..0110 0?..011000 l 00..0110 >> 2 -> 000..??01 l ~00..0110 -> 11..1001
16
Command Line Arguments int main(int argc, char *argv[ ]) { … int i = atoi(argv[1]); double f = atof(argv[2]); … } l argv[0] is the string of the name of evoking program. C.f. argv.cpp (old)
17
Summary of OOP l Information hiding and encapsulation with classes l Building new class from old (inheritance and hierarchy) l Polymorphism by function or operator overloading, and virtual functions.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.