CS201-37 - Introduction to Programming Lecture 37 Operator...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Introduction to Programming Lecture 37 Operator Overloading Operator Overloading Stream Insertion / Extraction int i ; cin >> i ; int a , b , c ; a + b + c ; cin >> i >> j ; Friend Function Member Operators Object.data Object.function ( ) Stream Insertion Operator int i = 5 , j = 10 , k = 15 ; cout << i << j << k ; Return type: Reference to the output stream Operator ostream & operator << ( ostream & output , vehicle A ) Reference to the output stream } } Object of the class Definition ostream & operator << ( ostream & output , vehicle d ) { output<< d.seats ; output<<d.tires ; ­­­­­­­ return output ; } cout << d ; cout << “The description of the vehicle is \n” << d ; 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 ) ; } ; 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 ; } int i ; cin >> i ; Matrix x ; cin >> x ; 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 ) ; }; 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; } Example Matrix m ; m.getMatrix ( ) ; m.displayMatrix ( ) ; Example Matrix m ; cin >> m ; cout << m ; ...
View Full Document

This note was uploaded on 01/12/2010 for the course CS CS 201 taught by Professor Dr.naveedmalik during the Spring '09 term at Virtual University of Pakistan.

Ask a homework question - tutors are online