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 37

2 Operator Overloading

3 Stream Insertion / Extraction
Operator Overloading Stream Insertion / Extraction

4 int i ; cin >> i ;

5 int a , b , c ; a + b + c ;

6 cin >> i >> j ;

7 Friend Function

8 Member Operators

9 Object.data Object.function ( )

10 Stream Insertion Operator

11 int i = 5 , j = 10 , k = 15 ; cout << i << j << k ;

12 ostream & operator << ( ostream & output , vehicle A )
Return type: Reference to the output stream Operator } } ostream & operator << ( ostream & output , vehicle A ) Reference to the output stream Object of the class

13 Definition ostream & operator << ( ostream & output , vehicle d ) { output<< d.seats ; output<<d.tires ; return output ; }

14 cout << d ;

15 cout << “The description of the vehicle is \n” << d ;

16 Example class Matrix { private :
          int rows , cols ;           int elements [ 3 ] [ 3 ] ; public : Matrix ( int rows = 3 , int cols = 3 ) ;   friend ostream & operator << ( ostream & output , Matrix m ) ; } ;

17 Example ostream& operator << ( ostream & output , Matrix m ) {
for ( int i = 0 ; i < m.rows ; i ++ )     {         for ( int j = 0 ; j < m.cols ; j ++ )         {           output << m.elements [ i ] [ j ] ;         }     }     return output ; }

18 int i ; cin >> i ;

19 Matrix x ; cin >> x ;

20 Example class Matrix { private : int rows, cols ;
int elements [ 3 ] [ 3 ] ; public : Matrix ( int rows = 3 , int cols = 3 ) ; friend ostream & operator << ( ostream & output , Matrix m ) ;   friend istream & operator >> ( istream & input , Matrix m ) ; };

21 Example istream & operator >> ( istream & input , Matrix & m ) { cout<< “Please enter the values of the matrix” ;     for ( int i = 0 ; i < m.rows ; i ++ )     {         for ( int j = 0 ; j < m.cols ; j ++ )         {           cout << “Please enter the values of elements ” << i << “,” << j ; input >> m.elements [ i ] [ j ] ;         }     }     return input; }

22 Example Matrix m ; m.getMatrix ( ) ; m.displayMatrix ( ) ;

23 Example Matrix m ; cin >> m ; cout << m ;


Download ppt "Introduction to Programming"

Similar presentations


Ads by Google