Docsity

Operator Overloading and Stream Insertion/Extraction in C++, Slides of Computer Programming

Partial preview of the text

Download Operator Overloading and Stream Insertion/Extraction in C++ and more Slides Computer Programming in PDF only on Docsity!

Introduction to Programming

Lecture 37

Operator Overloading

int i ; cin >> i ;

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

Friend Function

Member Operators

Stream Insertion Operator

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

ostream & operator << ( ostream & output , vehicle d ) { output<< d.seats ; output<<d.tires ;


return output ; } Definition

cout << 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 ; }

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 ) ; };