Operator Overloading in C Updated 11112003 Copyright Kip

  • Slides: 37
Download presentation
Operator Overloading in C++ Updated 11/11/2003 Copyright Kip Irvine, 2003. All rights reserved. Only

Operator Overloading in C++ Updated 11/11/2003 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. 1

Overview l Operator Overloading Basics • Commonly overloaded operators • Requirements l Time Class

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

Operator Overloading Basics l Permit standard operators to be used with your class objects

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

Commonly Overloaded Operators l Unary ++, --, ( ), [ ], +, - l

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

Requirements l l Must be nonstatic member, or global function having at least 1

Requirements l l 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 ); Copyright Kip Irvine, 2003 5

Requirements l (cont) Cannot change operator precedence • binary * will be higher than

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

Time Class class Time { public: Time( unsigned int c = 0 ); //

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

Overloading ++ l l Prefix and postfix increment operators Time class: increment the minutes.

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

Prefix ++ // Prefix increment: add 1 to minutes. If // end of hour

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; } Copyright Kip Irvine, 2003 9

Postfix ++ // postfix increment: return the current // time, then increment the minutes.

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

Addition-Assignmment ( += ) // Add n minutes to the time. const Time &

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 % 24; // roll to next day return *this; } Copyright Kip Irvine, 2003 11

Less-Than Operator ( < ) bool operator <( const Time & rhs ) const

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( t 1 < t 2 ). . . Copyright Kip Irvine, 2003 12

Implcit Convert-to-int class Time { operator int( ) const { return (hours * 100)

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

Implcit Convert-to-string class Time { operator string( ) const { ostrstream os; os <<

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

Stream Output ( << ) Global function, declared as a friend by the Time

Stream Output ( << ) Global function, declared as a friend by the Time class: // 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; } Copyright Kip Irvine, 2003 15

Suppose it were a Member Function Then it would be declared like this: ostream

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

Suppose it were a Member Function. . . and called like this: Time t

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

Short Diversion: Exception Handling Copyright Kip Irvine, 2003 18

Short Diversion: Exception Handling Copyright Kip Irvine, 2003 18

Default Exception Class l l Default C++ Exception class. Container classes override this. what(

Default Exception Class l l 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; }; Copyright Kip Irvine, 2003 19

Define an Exception Class #include <exception> class Range. Error : public exception { public:

Define an Exception Class #include <exception> class Range. Error : public exception { public: Range. Error( const char * fname, unsigned line, unsigned subscr ); friend ostream & operator <<( ostream & os, const Range. Error & R ); const char * what( ) const; private: string file. Name; unsigned line. Number; unsigned value; }; Copyright Kip Irvine, 2003 20

Exception Constructor Range. Error: : Range. Error( const char * fname, unsigned line, unsigned

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

Implement what( ) const char * Range. Error: : what( ) const { return

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

Throw an Exception class Time { void set. Hours( unsigned h ) { if(

Throw an Exception class Time { void set. Hours( unsigned h ) { if( h > Hour. Max ) throw Range. Error( __FILE__, __LINE__, h ); hours = h; } //. . . }; Copyright Kip Irvine, 2003 23

Using try. . . catch Time t 1; try { t 1. set. Hours(

Using try. . . catch Time t 1; try { t 1. set. Hours( 25 ); } catch( const Range. Error & R ) { cout << R; } Copyright Kip Irvine, 2003 24

Student Class Example l l Overloads <, =, ==, <<, >> Student. Vector class

Student Class Example l l Overloads <, =, ==, <<, >> Student. Vector class Copyright Kip Irvine, 2003 25

Student Class class Student { public: Student(); Student( const string & id, const string

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

Overloading < bool operator <( const Student & S 2 ) { return m_ID

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

Overloading = Student & operator =( const Student & S 2 ) { //

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

The vector Class l l Expands automatically Supports the subscript operator, which does not

The vector Class l l 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<int> my. List; my. List. push_back( 20 ); my. List. push_back( 30 ); my. List[2] = 25; // error! Copyright Kip Irvine, 2003 29

Using a Class to Encapsulate a Vector l l We can create our own

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

Our Collection Class Can. . . l l l Act as a wrapper around

Our Collection Class Can. . . l l l 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 subscript operator is implemented Throw an exception when a subscript is out of range Copyright Kip Irvine, 2003 31

Student. Vector Class Example class Student. Vector { public: Student. Vector( int capacity =

Student. Vector Class Example class Student. Vector { public: Student. Vector( 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<Student> v. Students; }; Copyright Kip Irvine, 2003 32

Overloading the [ ] Operator Returns a modifiable reference to a student. Permits the

Overloading the [ ] Operator Returns a modifiable reference to a student. Permits the collection to be modified. Student & operator []( int j ) { if( j < 0 || j >= v. Students. size( ) ) throw Range. Error( __FILE__, __LINE__, j ); return v. Students[ j ]; } Copyright Kip Irvine, 2003 33

Calling the [ ] Operator Use this operator to insert a student in the

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

Overloading the [ ] Operator (cont) This version returns a constant reference. const Student

Overloading the [ ] Operator (cont) This version returns a constant reference. const Student & operator [](int j) const { if( j < 0 || j >= v. Students. size( ) ) throw Range. Error( __FILE__, __LINE__, j ); return v. Students[ j ]; } Copyright Kip Irvine, 2003 35

Calling the const & [ ] Operator This version of the operator is called

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

The End Copyright Kip Irvine, 2003 37

The End Copyright Kip Irvine, 2003 37