Docsity

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

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