Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming

Similar presentations


Presentation on theme: "Introduction to Programming"— Presentation transcript:

1 Introduction to Programming
Lecture 41

2 Templates

3 Types of Templates Function Templates Class Templates

4 Swap Function { int temp ; temp = i ; i = j ; j = temp ; }
void swap ( int & i , int & j ) { int temp ; temp = i ; i = j ; j = temp ; }

5 Function Overloading

6 Function Templates

7 template < class T >

8 return_type function_name ( argument_list )

9 Example int reverse ( int x ) { return ( - x ) ; }
double reverse ( double x )

10 Example template < class T > T reverse ( T x ) { return (- x ) ;
}

11 Example main ( ) { int i ; ……. reverse ( i ) ; }

12 Example main ( ) { int i ; … reverse ( i ) ; double y ;
reverse ( y ) ; }

13 Code Reuse

14 Example template < class T > void swap ( T & x , T & y ) {
T temp ; temp = x ; x = y ; y = temp ; }

15 int a , b ; char a , b ; swap ( a , b ) ;

16 Example template < class T > void swap ( T & x , T & y ) {
T temp ; temp = x ; x = y ; y = temp ; }

17 template < class T , class U >

18 Example template <class T> T larger ( T x, T y ) { T big ;
if ( x > y ) big = x ; else big = y ; return ( big ) ; }

19 Example main ( ) { int i = 5 , j = 7 ; double x = 10.0 , y = 15.0 ;
cout << larger ( i , j ) << endl ; cout << larger ( x , y ) << endl ; // cout << larger ( i , y ) ; Error }

20 Example template <class T> void inverse ( T & x , T & y ) {
T temp ; temp = x ; x = y ; y = temp ; }

21 Example template <class T> T inverse ( T x ) { return ( - x ) ;
}

22 Example main ( ) { int i = 4 , j = 8 ; inverse ( i , j ) ;
}

23 Example template <class T> T reverse ( T x ) { return ( - x ) ;
} void main ( ) double a = ; reverse ( a ) ; reverse <int> ( a ) ;

24 Example template <class T , class U> T reverse ( U x ) {
return ( - x ) ; }

25 Example main ( ) { double a = 8.8 ; reverse ( a ) ;
reverse <int> ( a ) ; reverse <int , double> ( a ) ; reverse<double , double> ( a ) ; reverse<double , int> ( a ) ; }

26 Example class PhoneCall { private : int lengthOfCall ; char billCode ;
public : PhoneCall ( const int i , char b ) ; PhoneCall ( PoneCall & p ) ; PhoneCall PhoneCall :: operator - ( void ) ; void display ( void ) ; } ;

27 Example template <class T> T reverse ( T x ) { return ( - x ) ;
}

28 Example PhoneCall reverse ( PhoneCall x ) { return (- x ) ; }

29 Example PhoneCall PhoneCall :: operator - ( void ) {
PhoneCall temp ( * this ) ; temp.billCode = 'C' ; return ( temp ) ; }

30 Example main ( ) { PhoneCall a ( 10 , ‘S’ ) ; a.display ( ) ;
a = reverse ( a ) ; }


Download ppt "Introduction to Programming"

Similar presentations


Ads by Google