Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Operator Overloading in C++ Copyright Kip Irvine, 2003. All rights reserved. Only students enrolled in COP 4338 at Florida International University may.

Similar presentations


Presentation on theme: "1 Operator Overloading in C++ Copyright Kip Irvine, 2003. All rights reserved. Only students enrolled in COP 4338 at Florida International University may."— Presentation transcript:

1 1 Operator Overloading in C++ Copyright Kip Irvine, 2003. All rights reserved. Only students enrolled in COP 4338 at Florida International University may copy or print the contents of this slide show. Some materials used here are from Mark Allen Weiss, used by permission. Updated 11/11/2003

2 Copyright Kip Irvine, 2003 2 Overview Operator Overloading Basics Commonly overloaded operators Requirements Time Class Exception handling example Overloading ++, +=, < Implicit conversion operators Stream output ( << ) Using a Class to Encapsulate a vector StudentVector class overloading [ ] Stream output ( << )

3 Copyright Kip Irvine, 2003 3 Operator Overloading Basics Permit standard operators to be used with your class objects keep the traditional semantics Operator always associated with a class may or may not be a member function Unary and binary operators Syntax: retType operator op ( paramlist ) op is some standard operator symbol

4 Copyright Kip Irvine, 2003 4 Commonly Overloaded Operators Unary ++, --, (increment, decrement) ( ), (function call) [ ],(subscript) +,  (sign) Binary +, -, *, /, %(arithmetic) =, +=, -+, *=, /=, %=(assignment) &, |, ^, ^=, &=, |=(bitwise) ==, !=, >, =, <=(relational) ||, &&(logical) >(shift)

5 Copyright Kip Irvine, 2003 5 Requirements Must be nonstatic member, or global function having at least 1 class parameter Cannot overload operators dealing with only primitives example: int operator + ( int x, int y );

6 Copyright Kip Irvine, 2003 6 Requirements (cont) Cannot change operator precedence binary * will be higher than binary + Cannot change the number of operands for example, operator / cannot be unary operator ~ cannot be binary Cannot change associativity Example: 6 2 3 implies pow(6, pow(2,3)) should not be written as 6^2^3, because ^ associates left to right

7 Copyright Kip Irvine, 2003 7 Time Class class Time { public: Time( unsigned int c = 0 );// constructor Time( const Time & t );// constructor operator int( ) const// convert to int operator string( ) const// convert to string const Time & operator ++( );// prefix increment Time operator ++( int );// postfix increment bool operator <( const Time & rhs ) const// less-than const Time & operator +=( unsigned n );// add-assign friend ostream & operator <<( ostream & os, // stream output const Time & h ); private: unsigned hours; unsigned minutes; };

8 Copyright Kip Irvine, 2003 8 Overloading ++ Prefix and postfix increment operators Time class: increment the minutes. const Time & operator ++( );// prefix Time operator ++( int );// postfix Time T( 1245 );// 12:45 pm T++;// 12:46 pm ++T;// 12:47 pm

9 Copyright Kip Irvine, 2003 9 Prefix ++ // Prefix increment: add 1 to minutes. If // end of hour reached, reset to beginning // of next hour. const Time & operator ++( ) { if( ++minutes > 59 ) { minutes = 0; hours = ( hours + 1) % ( 24 ); } return *this; }

10 Copyright Kip Irvine, 2003 10 Postfix ++ // postfix increment: return the current // time, then increment the minutes. Time operator ++( int ) { Time save( *this ); // construct a copy operator ++( ); // increment the time return save; // return the copy }

11 Copyright Kip Irvine, 2003 11 Addition-Assignmment ( += ) // Add n minutes to the time. const Time & operator +=( unsigned n ) { unsigned t = minutes + n; minutes = t % 60; // remaining minutes hours += (t / 60); // add to hours hours = hours % 24; // roll to next day return *this; }

12 Copyright Kip Irvine, 2003 12 Less-Than Operator ( < ) bool operator <( const Time & rhs ) const { if( hours < rhs.hours ) return true; else if( hours == rhs.hours ) return minutes < rhs.minutes; else return false; } called as: if( t1 < t2 )...

13 Copyright Kip Irvine, 2003 13 Implcit Convert-to- int class Time { operator int( ) const { return (hours * 100) + minutes; } //... }; called as: Time t1( 1830 ); int n = t1;

14 Copyright Kip Irvine, 2003 14 Implcit Convert-to- string class Time { operator string( ) const { ostrstream os; os << hours << ":" << minutes << '\0'; return os.str( ); } //... }; called as: Time t1( 1830 ); string s = t1;

15 Copyright Kip Irvine, 2003 15 Stream Output ( << ) // Display in "hh:mm" format. ostream & operator <<( ostream & os, const Time & t ) { os.fill( '0' ); os << setw( 2 ) << t.hours << ':' << setw( 2 ) << t.minutes; return os; } Global function, declared as a friend by the Time class:

16 Copyright Kip Irvine, 2003 16 Suppose it were a Member Function ostream & operator <<( ostream & os ) { os.fill( '0' ); os << setw( 2 ) << hours << ':' << setw( 2 ) << minutes; return os; } Then it would be declared like this:

17 Copyright Kip Irvine, 2003 17 Suppose it were a Member Function Time t1( 1830 ); t1 << cout; or this: t1.operator <<( cout );...and called like this:

18 Copyright Kip Irvine, 2003 18 Short Diversion: Exception Handling

19 Copyright Kip Irvine, 2003 19 Default Exception Class Default C++ Exception class. Container classes override this. what( ) returns a description class exception { public: exception( ); exception( const exception & rhs ); exception & operator=( const exception & rhs ); virtual ~exception( ); virtual const char *what( ) const; };

20 Copyright Kip Irvine, 2003 20 Define an Exception Class #include class RangeError :public exception { public: RangeError( const char * fname, unsigned line, unsigned subscr ); friend ostream & operator <<( ostream & os, const RangeError & R ); const char * what( ) const; private: string fileName; unsigned lineNumber; unsigned value; };

21 Copyright Kip Irvine, 2003 21 Exception Constructor RangeError::RangeError( const char * fname, unsigned line, unsigned subscr ) { fileName = string( fname ); // trim path from filename int pos = fileName.find_last_of( "\\" ); if( pos != string::npos ) fileName = fileName.substr( pos+1 ); lineNumber = line; value = subscr; }

22 Copyright Kip Irvine, 2003 22 Implement what( ) const char * RangeError::what( ) const { return "RangeError exception"; }

23 Copyright Kip Irvine, 2003 23 Throw an Exception class Time { void setHours( unsigned h ) { if( h > HourMax ) throw RangeError( __FILE__, __LINE__, h ); hours = h; } //... };

24 Copyright Kip Irvine, 2003 24 Using try...catch Time t1; try { t1.setHours( 25 ); } catch( const RangeError & R ) { cout << R; }

25 Copyright Kip Irvine, 2003 25 Student Class Example Overloads > StudentVector class

26 Copyright Kip Irvine, 2003 26 Student Class class Student { public: Student(); Student( const string & id, const string & lname ); bool operator < (const Student & S2 ); Student & operator =(const Student & S2 ); bool operator ==( const Student & S2 ); friend ostream & operator <<(ostream & out, const Student & S); friend istream & operator >>(istream & inp, Student & S); private: string m_ID; string m_LastName; };

27 Copyright Kip Irvine, 2003 27 Overloading < bool operator <( const Student & S2 ) { return m_ID < S2.m_ID; }

28 Copyright Kip Irvine, 2003 28 Overloading = Student & operator =( const Student & S2 ) { // if assigning object to itself... if( *this == S2 ) return *this; m_ID = S2.m_ID; m_LastName = S2.m_LastName; return *this; }

29 Copyright Kip Irvine, 2003 29 The vector Class Expands automatically Supports the subscript operator, which does not check subscript ranges OS runtime error can appear "late", after a lot of other valid code has finished executing Example: vector myList; myList.push_back( 20 ); myList.push_back( 30 ); myList[2] = 25;// error!

30 Copyright Kip Irvine, 2003 30 Using a Class to Encapsulate a Vector We can create our own class that encapsulates a particular type of vector Example: rather than using vector, we will create StudentVector

31 Copyright Kip Irvine, 2003 31 Our Collection Class Can... Act as a wrapper around the vector class Limit contents to Student or Student-derived objects Provide additional functions and operators that improve the vector semantics Show how subscript operator is implemented Throw an exception when a subscript is out of range

32 Copyright Kip Irvine, 2003 32 StudentVector Class Example class StudentVector { public: StudentVector( int capacity = 0 ); void add( const Student & S ); Student & operator []( int j ); const Student & operator []( int j ) const; Student at( int j ) const; private: vector vStudents; };

33 Copyright Kip Irvine, 2003 33 Overloading the [ ] Operator Returns a modifiable reference to a student. Permits the collection to be modified. Student & operator []( int j ) { if( j = vStudents.size( ) ) throw RangeError( __FILE__, __LINE__, j ); return vStudents[ j ]; }

34 Copyright Kip Irvine, 2003 34 Calling the [ ] Operator Use this operator to insert a student in the vector: StudentVector vec( 10 ); vec[0] = Student( "12345", "Jones" );

35 Copyright Kip Irvine, 2003 35 Overloading the [ ] Operator (cont) This version returns a constant reference. const Student & operator [](int j) const { if( j = vStudents.size( ) ) throw RangeError( __FILE__, __LINE__, j ); return vStudents[ j ]; }

36 Copyright Kip Irvine, 2003 36 Calling the const & [ ] Operator This version of the operator is called when you do not try to modify the returned value: StudentVector vec( 10 ); cout << vec[0];

37 Copyright Kip Irvine, 2003 37 The End


Download ppt "1 Operator Overloading in C++ Copyright Kip Irvine, 2003. All rights reserved. Only students enrolled in COP 4338 at Florida International University may."

Similar presentations


Ads by Google