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

The concepts of operator overloading and stream insertion/extraction in c++. It includes examples of overloading the '<<' operator for a 'vehicle' class and a 'matrix' class, as well as code snippets demonstrating the use of these operators. Students will learn how to define and implement operator functions, and how to use these operators to input and output data.

Typology: Slides

2011/2012

Uploaded on 11/06/2012

somo
somo 🇮🇳

4.8

(4)

70 documents

1 / 23

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Introduction to Programming
Lecture 37
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

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