260 likes | 273 Views
This lecture introduces operator overloading in programming, covering binary and unary operators, member and non-member operators, and code reuse through comparison operators. Examples and implementation details are provided.
E N D
Introduction to Programming Lecture 32
In Last Lecture • What is operator overloading ? • Overload operators We also saw the • Binary Operators • Unary Operators • Member and Non-member operators
Example Complex operator - ( Complex c ) ;
Example Complex Complex :: operator - ( Complex c ) { Complex Temp ; Temp.real = real - c.real ; Temp.imag = imag - c.imag ; return Temp ; }
Example void operator -= ( Complex c ) ;
Example void Complex :: operator -= ( Complex c ) { real -= c.real ; imag -= c.imag ; }
Example Date Date :: operator + ( int days ) { Date Temp ; int toHold ; int daysInThisMonth = 0 ; daysInThisMonth = daysInMonth ( month ) ; toHold = days ;
Example if ( ( day + days ) >= daysInThisMonth ) { Temp.month = month + 1 ; if ( Temp.month > 12 ) { Temp.day = 1 ; Temp.month = 1 ; Temp.year = year + 1 ; }
Example else { toHold = day + days ; if ( toHold > daysInThisMonth ) { Temp.day = toHold - daysInThisMonth ; } Temp.year = year ; } }
Example else { Temp.day = days + day ; Temp.month = month ; Temp.year = year ; } return Temp ; }
i ++ i --
Example void Date :: operator ++ ( ) { if ( day == daysOfMonth ( day , month , year ) ) { if ( month < 12 ) { day = 1 ; month ++ ; } else { day = 1 ; month = 1 ; year ++ ; } else day ++ ; }
Example Date Date :: operator + ( int days ) { Date Temp ; for ( i = 1 ; i < days ; i ++ ) ++ Temp ; return Temp ; } days = 5
Comparison Operator < > <= >= ==
Example Date d1 , d2 ; if ( d1 > d2 )
Example Date date ; date + 5 ;
Example 5 + date ;