42
1 Overloading Lesson #8 ote: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Dee

1 Overloading Lesson #8 Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek

  • View
    217

  • Download
    1

Embed Size (px)

Citation preview

1

Overloading

Lesson #8

Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek

2

Content

Function Overloading Operator Overloading

3

Function Overloading

The ability to give several functions the same name provided the parameters for each of the functions differ in either: number type order

4

Function Overloading

A mechanism for multiple functions with the same name (similar concept to polymorphism).

In C++, a function is identified by not only the name but also the number, the order and the types of the parameters, which is called the signature.

5

Example

void swap (unsigned long &, unsigned long &)

void swap (double &, double &) void swap (char &, char &) void swap (Point &, Point &) Each is a different function!!!

6

Poor Practice

Class Student{

Public:

Unsigned credits();//Get the credits

Unsigned credits(unsigned n);//Set the credits with n

}

That is to say, functions with the same names should have similar functionality.

7

Overloading Constructors

// Overloading Constructors#include <iostream.h>class Point {public: Point( int xx = 0, int yy = 0 )

{x= xx; y = yy;cout << "Point constructor."<<endl;};

private:int x,y;

};

8

Overloading Constructors

class Figure {public: Figure(){cout << "Default

constructor."<<endl;}; Figure( const Point & center ){cout << "2nd

constructor."<<endl;}; Figure( const Point vertices[], int count ){cout

<< "3rd constructor."<<endl;};};

9

Overloading Constructors

int main()

{Figure fig1[3];

Point center( 25, 50 );

Figure fig2( center );

const int VCount = 5;

Point verts[VCount];

Figure fig3( verts, VCount );

return 0;

}

10

11

12

istream

istream & get ( char &); istream & get ( signed char &); istream & get (unsigned char &); int get();

13

istream

#include <iostream.h>main(){ char ch; signed char sch; unsigned char uch; cin.get (ch); cin.get (sch); cin.get (uch); ch = cin.get()}

14

Argument Conversion

void calculate (long p1, long p2, double p3, double p4);

long a1 = 12345678; int a2 = 1; double a3 = 2.34567456; float a4 = 3.1; calculate(a1, a2, a3, a4); //Correct!!!

//Conversion! Assignment-compatible!!! Student S; calculate(S, 10, 5.5, 6)// Incompatible!!

15

Overloading Resolution

Best-matching function principle: For each argument, the compiler finds the

set of all functions that best match the parameter.

If more than one function results from the intersection, an error results.

16

Example void display (int x); //version1 void display (float y); //version2 int i; float f; double d; display(i); //version1 display(f); //version2 display(d); // I do not know which one !!!

17

Another Example

void print (float a, float b) {cout << “version1”<<endl;} void print (float a, int b) {cout << “version2”<<endl;}

18

Another Example

main(){ int i, j; float f; double d; print (i,j); // version2 print (i,f); // version1 print (d,f); // version1}

19

Another Example print (d,3.5); // error print (i,4.5); // error print (d,3.0); // error print (i,d); // errorCasting makes it work print (i,int(10L)); // version2 print (f,float(10L)); // version1 print (d,float(3.0)); // version1 print (i,int(d)); // version2, ex8-6.cpp

20

Operator Overloading

Refers to the technique of ascribing new meaning to standard operators such as +, >>, = … when used with class operands.

In fact, it is a way to name a function. Using the same name with some normal

operators, makes the program more readable.

21

Operator OverloadingDefine an overloaded operator in class Aclass:

class Aclass

{public:

int operator +(Aclass &a){};

}

Aclass a, b;

int i;

i = a+b;// i = a.operator +(b);

22

Example of Operator Overloading

The ‘+’ symbol has been overloaded to represent: integer addition floating-point addition pointer addition

23

Operators Allowing Overloading

Unary Operators new, delete, new[], delete[], ++, --, (), [], +, -, *, &, !, ~,

Binary operators +, -, *, /, %, =, +=, -=, *=, /=, %=, &, |, ^,

^=, &=, |=, ==, !=, >, <, >=, <=, ||, &&, <<, >>, >>=, <<=, ->, ->*

24

Operators that do not Allow Overloading

. member access .* member access-dereference :: scope resolution ?: arithmetic-IF

25

Restrictions

Neither the precedence nor the associativity of an operator can be changed.

Default arguments cannot be used. The “arity” of the operator cannot be

changed. Only existing operators may be

overloaded.

26

Arithmetic Operators

#include <iostream.h> #include <iomanip.h> #include "range.h" // RangeError class const unsigned HourMax = 23; const unsigned MinuteMax = 59;

27

The Time Class class Time { public: Time( unsigned c = 0 ); Time( const Time & t ); void SetHours( unsigned h ); void SetMinutes( unsigned m ); const Time & operator ++(); Time operator ++(int); const Time & operator +=( unsigned n ); friend ostream & operator <<( ostream & os, const Time & h ); private: unsigned hours; unsigned minutes; };

28

The Time Class

Time::Time( unsigned tv ) //tv --1845..18:45 { SetHours(tv / 100); //quotient

SetMinutes(tv % 100); //remainder } Time::Time( const Time & t2 ) { minutes = t2.minutes; hours = t2.hours; }

29

The Time Class void Time::SetHours( unsigned h ) { if( h > HourMax ) throw RangeError(__FILE__,__LINE__,h); hours = h; }

void Time::SetMinutes( unsigned m )

{

if( m > MinuteMax ) throw RangeError(__FILE__,__LINE__,m);

minutes = m;

}

30

Overloading unary operators

const Time & Time::operator ++() { if( ++minutes > MinuteMax ) { minutes = 0; hours = (hours + 1) % (HourMax + 1); } return *this; }

31

Overloading unary operators

Time Time::operator ++( int ) { Time save( *this ); // construct a copy operator ++(); // increment the time return save; // return the copy }

32

Overloading Binary Operators

const Time & Time::operator +=( unsigned n ) { unsigned t = minutes + n; minutes = t % (MinuteMax + 1); // remaining minutes hours += t / (MinuteMax + 1); // add to hours hours = hours % (HourMax + 1); // roll over to next day return *this; }

33

The Time Class ostream & operator <<( ostream & os, const Time & t ) { os.fill('0'); os << setw(2) << t.hours << ':' << setw(2) <<

t.minutes; // os << t.hours << ':' << t.minutes<<', ' ; return os; }

34

void test(){ Time a;Time b(1845);Time c(2359);cout << ++a << '\n' // 00:01 << b++ << endl; // 18:45//operator <<(cout, b++);cout << (c += 15) << '\n' // 00:14//cout << c.operator += (15) << '\n'<< (b += 20) << '\n'; // 19:06Time d(1230);for(unsigned i = 0; i < 50; i++) cout << ++d << ", ";cout << endl;}

35

The Time Class

int main() { try { test(); } catch( const RangeError & R ) { cout << R; } return 0; }//ex8time.cpp

36

“=“ operators and Copy constructor

The “=“ (Assignment) can also be overloaded (another method to define the copy constructor).

37

Copy constructorTranscript::Transcript( const Transcript & T )

{

count = T.count;

courses = new FString[MaxCourse];

for(unsigned i = 0; i < count; i++)

courses[i] = T.courses[i];

cout <<"copy constructor."<<endl;

}

38

Assignment operatorTranscript & Transcript::operator =( const Transcript &

T ){ if( this != &T ) // not the same object? { delete [] courses; courses = new FString[MaxCourse]; count = T.count; for(int i = 0; i < count; i++) courses[i] = T.courses[i]; } cout <<"= operator."<<endl; return *this;}

39

main()void mainsub(){ Transcript T1; Transcript T2( T1 ); // copy constructor Transcript T4 = T1 ; // copy constructor Transcript T3; T3 = T1; // assignment operator}int main(){ mainsub(); return 0;}

40

41

42

Reading

Readings: Chapter 9 Section 9.1