Stream and Extraction Operator Overloading in Object-Oriented Programming (OOP), Slides of Object Oriented Programming

How to overload the stream and extraction operators in object- oriented programming (oop) using the example of a complex class. It covers the use of the stream insertion operator '<<' and the stream extraction operator '>>' and their implementation in the complex class. The document also includes the main program and its output.

Typology: Slides

2011/2012

Uploaded on 08/08/2012

anchita
anchita 🇮🇳

4.4

(7)

113 documents

1 / 20

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Object-Oriented Programming
(OOP)
Lecture No. 19
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Stream and Extraction Operator Overloading in Object-Oriented Programming (OOP) and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)Lecture No. 19

Stream Insertion operator^ ►Often we need to display the dataon the screen^ ►Example:^ int i=1, j=2;cout << “i= ”<< i << “\n”;Cout << “j= ”<< j << “\n”;

Stream Insertion operator class Complex{… public:… void operator << (const

Complex & rhs);

Stream Insertion operator int main(){Complex c1;cout << c1;

// Error c1 << cout;c1 << cout << 2; // Errorreturn 0;

Stream Insertion operator void^ Complex::operator

(ostream

&^ os){ os^ <<^ ‘(‘

<<^ real<< ‘,’ <<^ img

<<^ ‘)’;

Stream Insertion operator class^ Complex{...friend

ostream

&^ operator

(ostream

&^ os,^ const^ Complex&^

c);

};^ Note: this objectis NOT

const

Note: return typeis NOT^ const

Stream Insertion operator^ Complex

c1(1.01,

c2(0.01,

cout^ << c1^ <<^ endl^ << c2;

Stream Insertion operator^ Output:^ (^

1.01^ ,^
20.1^ )
(^ 0.^
,^ 12.^

Stream Extraction Operator^ ►Overloading

“>>”^ operator:

class^ Complex{...friend

istream

&^ operator

^ (istream

&^ i,^ Complex

c);

};^

Note: this objectis NOT^ const

Stream Extraction Operator istream^

&^ operator

<<^ (istream &^ in,^ Complex

&^ c){ in^ >>^ c.real;in^ >>^ c.img;return^ in; }

Stream Extraction Operator^ Output:^ ( 1.0025 , 0.0241 )

Other Binary operators ►Overloading comparison operators:^ class Complex{public:bool operator == (const Complex & c);//friend bool operator == (const//Complex & c1, const Complex & c2);bool operator != (const Complex & c);//friend bool operator != (const//Complex & c1, const Complex & c2);… };

Other Binary operators^ bool operator ==(constComplex& lhs, const Complex& rhs){if((lhs.real == rhs.real) &&

(lhs.img == rhs.img)){return true;} elsereturn false;}

Other Binary operators^ bool Complex::operator !=(constComplex & c){if((real != c.real) ||

(img != c.img)){return true;} elsereturn false;}