Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 23

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 Object of the


stream 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 ;

You might also like