Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators...

27
1 Operator Overloading Operator Overloading Friend Functions & Forms Friend Functions & Forms CSC 330 Object Oriented Programming

Transcript of Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators...

Page 1: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

1

Operator OverloadingOperator OverloadingFriend Functions & FormsFriend Functions & Forms

CSC 330 Object Oriented Programming

Page 2: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

2

Most of C++’s operators can be overloadedMost of C++’s operators can be overloaded

.. Operators that can be overloaded

+ - * / % ^ & |

~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[]

Restrictions on Operator OverloadingRestrictions on Operator Overloading

No new operators can be createdUse only existing operators

Page 3: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

3

Restrictions on Operator OverloadingRestrictions on Operator Overloading cont’dcont’d

Arity (number of operands) cannot be changedArity (number of operands) cannot be changedUnary operators remain unary, and binary operators remain Unary operators remain unary, and binary operators remain binarybinaryOperators Operators &&, , **, , ++ and and -- each have unary and binary each have unary and binary versionsversions

Unary and binary versions can be overloaded separatelyUnary and binary versions can be overloaded separately

Page 4: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

4

Overloading OperatorsOverloading Operators——The RulesThe Rules

Associativity Associativity refers to refers to the order in which the order in which actions within an actions within an expression are carried expression are carried outoutYou cannot change You cannot change associativity when you associativity when you overload operatorsoverload operatorsYou also cannot change You also cannot change the normal precedence the normal precedence of any operatorof any operator

Page 5: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

5

Overloading OperatorsOverloading Operators——The RulesThe Rules

Page 6: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

6

A A ComplexComplex ClassClass

#include <iostream>

class Complex{

double real;double imag;

public:Complex(double re=0, double im=0){

this->real = re;this->image = im;

}Complex add(const Complex& c) const{

Complex result;result.real = this->real + c.real;result.imag = this->imag + c.imag;return result;

}....

};

Page 7: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

7

Using the Using the ComplexComplex ClassClass

int main(){

Complex z(1,2), w(3,4);Complex a = z.add(w); // want a = z+wa.display();

}

(4,6)

Page 8: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

8

Operator FunctionsOperator Functions

operatoroperator keyword together with an operatorkeyword together with an operatoroperator+operator+

operatoroperator--

etc.etc.

Can overload all operators except:Can overload all operators except:::::..**

?:?:

Page 9: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

9

ComplexComplex with with operator+operator+

class Complex{

// ...public:

// ...Complex operator+(const Complex& c) const{

Complex result;result.real = this->real + c.real;result.imag = this->imag + c.imag;return result;

}// ...

};

int main(){

Complex z(1,2), w(3,4);Complex a = z + w; // z.operator+(w)a.display();

}

Page 10: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

10

Global Global ComplexComplex OperatorsOperators

class Complex{public:

Complex(double real = 0, double imag = 0){

this->real = real;this->imag = imag;

}double getReal() const {return real;}double getImag() const {return imag;}// ...

};

Complex operator+(const Complex& c1, const Complex& c2){

double real = c1.getReal() + c2.getReal();double imag = c1.getImag() + c2.getImag();Complex result(real, imag);return result;

}

Page 11: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

11

friendfriend FunctionsFunctions

class Complex {class Complex {public:public:

Complex( );Complex( ); // default// defaultComplex( double ) ; // real givenComplex( double ) ; // real givenComplex( double, double ) ; // both givenComplex( double, double ) ; // both givenvoid write( ) const; void write( ) const; // friend functions // friend functions friend Complex operator+( const Complex&, const Complex& ) ; friend Complex operator+( const Complex&, const Complex& ) ; friend Complex operatorfriend Complex operator--( const Complex&, const Complex& ) ;( const Complex&, const Complex& ) ;friend Complex operator*( const Complex&, const Complex& ) ;friend Complex operator*( const Complex&, const Complex& ) ;friend Complex operator/( const Complex&, const Complex& ) ;friend Complex operator/( const Complex&, const Complex& ) ;

private: private: double real; double real; double double imagimag;;

} ;} ;

Page 12: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

12

Implementation FileImplementation File

// Complex + as top// Complex + as top--level friendlevel friendComplex operator+( const Complex& t, const Complex& u ) {Complex operator+( const Complex& t, const Complex& u ) {

return Complex( return Complex( t.realt.real + + u.realu.real, , t.imagt.imag + + u.imagu.imag ) ;) ;}}// Complex // Complex -- as topas top--level friendlevel friendComplex operatorComplex operator--( const Complex& t, const Complex& u ) { ( const Complex& t, const Complex& u ) {

return Complex( return Complex( t.realt.real -- u.realu.real, , t.imagt.imag -- u.imagu.imag ) ;) ;}}// Complex * as top// Complex * as top--level friendlevel friendComplex operator*( const Complex& t, const Complex& u ) {Complex operator*( const Complex& t, const Complex& u ) {

return Complex( return Complex( t.realt.real * * u.realu.real -- t.imagt.imag * * u.imagu.imag,,t.imagt.imag * * u.realu.real + + t.realt.real * * u.imagu.imag ) ;) ;

}}// Complex / as top// Complex / as top--level friendlevel friendComplex operator/( const Complex& t, const Complex& u ) {Complex operator/( const Complex& t, const Complex& u ) {

double double abs_sqabs_sq = = u.realu.real * * u.realu.real + + u.imagu.imag * * u.imagu.imag; ; return Complex( (return Complex( (t.realt.real * * u.realu.real + + t.imagt.imag * * u.imag)/abs_squ.imag)/abs_sq,,

((t.imagt.imag * * u.realu.real -- tt--real * real * u.imag)/abs_squ.imag)/abs_sq););}}

Page 13: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

13

DiscussionsDiscussions

Friendship (i.e., using the friend keyword) is a complex and danFriendship (i.e., using the friend keyword) is a complex and dangerous topic for gerous topic for various reasons: various reasons:

Friendship, when applied to program design, is an Friendship, when applied to program design, is an escape mechanismescape mechanism allowing us to allowing us to circumvent the principles of encapsulation and data hiding. The circumvent the principles of encapsulation and data hiding. The use of friends use of friends should therefore be should therefore be minimizedminimized to situations where they can be used naturally. to situations where they can be used naturally.

If friends are used, realize that friend functions or classes beIf friends are used, realize that friend functions or classes become implementation come implementation dependent on the classes declaring them as friends. Once the intdependent on the classes declaring them as friends. Once the internal organization ernal organization of the data of a class declaring friends changes, all its friendof the data of a class declaring friends changes, all its friends must be recompiled s must be recompiled (and possibly modified) as well. (and possibly modified) as well.

Therefore, as a rule of thumb: Therefore, as a rule of thumb: don'tdon't use friend functions or classes. use friend functions or classes.

Page 14: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

14

Global Operator OverloadingGlobal Operator OverloadingSimilar to Similar to friendfriend Function Overloading, Except the Keyword Function Overloading, Except the Keyword friendfriend is Omitted and is Omitted and Global Functions CANNOT ACCESS Global Functions CANNOT ACCESS privateprivate Members Members

class Complex{ //All Public Members!class Complex{ //All Public Members!public:public:int real, image;int real, image;Complex(intComplex(int ip1 = 0, int ip2 = 0)ip1 = 0, int ip2 = 0)

:real(ip1), image(ip2){};:real(ip1), image(ip2){};};};void void operator!(Complexoperator!(Complex a)a){ {

int temp = int temp = a.reala.real; ; a.reala.real = = a.imagea.image; ; a.imagea.image = temp;= temp;coutcout << "Real: " << << "Real: " << a.reala.real << << endlendl;;coutcout << "Imaginary: " << << "Imaginary: " << a.imagea.image << << endlendl;;

}}

main()main(){{

Complex one(1,2);Complex one(1,2);!one;!one;

}}

Page 15: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

15

Overloading of Operators Having a Variable Overloading of Operators Having a Variable ArityArityOperators Such as Operators Such as -- Can be Unary or Binary Can be Unary or Binary Overloading of Such Operators Involves Creating a Unary FunctionOverloading of Such Operators Involves Creating a Unary Function (One (One Operand) and a Binary Function (Two Operands) Operand) and a Binary Function (Two Operands) Only if Both Forms are Used, They Need to be Implemented Only if Both Forms are Used, They Need to be Implemented

class Number{class Number{int n;int n;

public:public:Number(intNumber(int x = 0):n(x){}x = 0):n(x){}Number operatorNumber operator--(){n = (){n = --n; return *this;}n; return *this;}Number operatorNumber operator--(Number ip) (Number ip) {n = n {n = n –– ip.nip.n; return *this;}; return *this;}

};};main(){main(){

Number one(1), two(2), three;Number one(1), two(2), three;one = one = --one; //unary operatorone; //unary operatorthree = one three = one -- two; //two; //three.nthree.n = = --33

}}

Page 16: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

16

Operators with Prefix and Postfix Forms Operators with Prefix and Postfix Forms Separate Functions for Each Separate Functions for Each ---- Prefix and Prefix and Postfix Postfix ---- Forms are Needed Forms are Needed Prefix Form is Treated as an Unary Operator Prefix Form is Treated as an Unary Operator Postfix Form is Treated as a Binary Operator Postfix Form is Treated as a Binary Operator

Page 17: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

17

Prefix Overloaded Function Prefix Overloaded Function ---- Example Example class Number{class Number{

int n;int n;public:public:Number(intNumber(int x):n(xx):n(x){}; //Constructor){}; //Constructor//prefix operator //prefix operator ---- unaryunaryNumber operator++(); Number operator++();

};};Number Number Number::operatorNumber::operator++(){++(){

n++; return *this;}n++; return *this;}main(){main(){

Number one(10); //Number one(10); //one.none.n = 10= 10++one; //++one; //one.none.n = 11= 11

}}

Page 18: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

18

Postfix Overloaded Function Postfix Overloaded Function ---- Example Example Postfix Operator is Implemented as a Binary Operator with an Postfix Operator is Implemented as a Binary Operator with an intintArgument with a Default Value of 0 . When specifying an Argument with a Default Value of 0 . When specifying an overloaded operator for the postfix form of the increment or overloaded operator for the postfix form of the increment or decrement operator, the additional argument must be of type int;decrement operator, the additional argument must be of type int;specifying any other type generates an error. specifying any other type generates an error. class Number{class Number{

int n;int n;public:public:

Number(intNumber(int x):n(xx):n(x){}; //Constructor){}; //Constructor//postfix operator //postfix operator ---- binary binary ---- int argumentint argumentNumber Number operator++(intoperator++(int); );

};};Number Number Number::operator++(intNumber::operator++(int y)y)

{if (y != 0) n += y; else n++; return *this;}{if (y != 0) n += y; else n++; return *this;}

Page 19: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

19

Postfix overloaded functionPostfix overloaded function——Example (Cont)Example (Cont)main()main()

{{Number one(10); // Number one(10); // one.none.n = 10= 10one++; // one++; // one.none.n = 11= 11one.operator++(2); // one.operator++(2); // one.none.n = 13= 13

}}

There is no syntax for using the increment or decrement There is no syntax for using the increment or decrement operators to pass these values other than explicit invocation, aoperators to pass these values other than explicit invocation, as s shown in the preceding code. A more straightforward way to shown in the preceding code. A more straightforward way to implement this functionality is to overload the implement this functionality is to overload the addition/assignment operator (+=). addition/assignment operator (+=).

Page 20: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

20

Special Overloading Forms Special Overloading Forms A Few Operators Require Special Treatments During A Few Operators Require Special Treatments During

Overloading Overloading Conversion Operator Conversion Operator constconst Array Operator Array Operator Function Call Function Call ---- Parenthesis Operator Parenthesis Operator Stream Insertion Stream Insertion ---- <<<< Operator Operator Stream Extraction Stream Extraction ---- >>>> Operator Operator Pointer to Member Pointer to Member ---- -->> Operator Operator Assignment Operator Assignment Operator newnew Operator Operator deletedelete Operator Operator

Page 21: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

21

Overloading StreamOverloading Stream--Insertion and StreamInsertion and Stream--Extraction OperatorsExtraction Operators

Overloaded Overloaded << << andand >>>> operators operators Must have left operand of types Must have left operand of types ostreamostream &&, , istreamistream &&respectivelyrespectivelyIt must be a nonIt must be a non--member function (left operand not an member function (left operand not an object of the class)object of the class)It must be a It must be a friendfriend function if it accesses private data function if it accesses private data membersmembers

Page 22: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

22

1 // Fig. 18.3: fig18_03.cpp

2 // Overloading the stream-insertion and

3 // stream-extraction operators.

4 #include <iostream>

5

6 using std::cout;

7 using std::cin;

8 using std::endl;

9 using std::ostream;

10 using std::istream;

11

12 #include <iomanip>

13

14 using std::setw;

15

16 class PhoneNumber {

17 friend ostream &operator<<( ostream&, const PhoneNumber & );

18 friend istream &operator>>( istream&, PhoneNumber & );

19

20 private:

21 char areaCode[ 4 ]; // 3-digit area code and null

22 char exchange[ 4 ]; // 3-digit exchange and null

23 char line[ 5 ]; // 4-digit line and null

24 };

25

26 // Overloaded stream-insertion operator (cannot be

27 // a member function if we would like to invoke it with

28 // cout << somePhoneNumber;).

29 ostream &operator<<( ostream &output, const PhoneNumber &num )

30 {

Page 23: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

23

31 output << "(" << num.areaCode << ") "32 << num.exchange << "-" << num.line;33 return output; // enables cout << a << b << c;34 }3536 istream &operator>>( istream &input, PhoneNumber &num )37 {38 input.ignore(); // skip (39 input >> setw( 4 ) >> num.areaCode; // input area code40 input.ignore( 2 ); // skip ) and space41 input >> setw( 4 ) >> num.exchange; // input exchange42 input.ignore(); // skip dash (-)43 input >> setw( 5 ) >> num.line; // input line44 return input; // enables cin >> a >> b >> c;45 }4647 int main()48 {49 PhoneNumber phone; // create object phone5051 cout << "Enter phone Number in the form (123) 456-7890:\n";5253 // cin >> phone invokes operator>> function by 54 // issuing the call operator>>( cin, phone ).55 cin >> phone;5657 // cout << phone invokes operator<< function by58 // issuing the call operator<<( cout, phone ). 59 cout << "The phone Number entered was: " << phone << endl;60 return 0;61 }

Page 24: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

24

Enter phone Number in the form (123) 456-7890:(800) 555-1212The phone Number entered was: (800) 555-1212

Page 25: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

25

Example: Student ClassExample: Student Classclass Student {class Student {

public:public:

Student();Student();

Student( const string & id, const string & Student( const string & id, const string & lnamelname ););

boolbool operator <operator < (const Student & S2 );(const Student & S2 );

Student & Student & operator =operator =(const Student & S2 );(const Student & S2 );

boolbool operator ==operator ==( const Student & S2 );( const Student & S2 );

friend friend ostreamostream & & operator <<operator <<((ostreamostream & out, & out,

const Student & S);const Student & S);

friend friend istreamistream & & operator >>operator >>((istreamistream & & inpinp, Student & S);, Student & S);

private:private:

string string m_IDm_ID;;

string string m_LastNamem_LastName;;

};};

Page 26: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

26

Overloading <Overloading <

boolbool operator <( const Student & S2 ) operator <( const Student & S2 ) { { return return m_IDm_ID < S2.m_ID; < S2.m_ID;

}}

Page 27: Overloading - Computer ScienceOverloading Stream-Insertion and Stream-Extraction Operators Overloaded >operators Must have left operand of types ostream&, istream&

27

Overloading =Overloading =

Student & operator =( const Student & S2 ) Student & operator =( const Student & S2 ) {{// if assigning object to itself...// if assigning object to itself...if( *this == S2 )if( *this == S2 )

return *this;return *this;

m_IDm_ID = S2.m_ID;= S2.m_ID;m_LastNamem_LastName = S2.m_LastName;= S2.m_LastName;return *this;return *this;

}}