1 / 26

Introduction to Programming

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.

hursey
Download Presentation

Introduction to Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Programming Lecture 32

  2. In Last Lecture • What is operator overloading ? • Overload operators We also saw the • Binary Operators • Unary Operators • Member and Non-member operators

  3. Example Complex operator - ( Complex c ) ;

  4. Example Complex Complex :: operator - ( Complex c ) { Complex Temp ; Temp.real = real - c.real ; Temp.imag = imag - c.imag ; return Temp ; }

  5. Example void operator -= ( Complex c ) ;

  6. Example void Complex :: operator -= ( Complex c ) { real -= c.real ; imag -= c.imag ; }

  7. Date operator + ( int i ) ;

  8. Example Date Date :: operator + ( int days ) { Date Temp ; int toHold ; int daysInThisMonth = 0 ; daysInThisMonth = daysInMonth ( month ) ; toHold = days ;

  9. Example if ( ( day + days ) >= daysInThisMonth ) { Temp.month = month + 1 ; if ( Temp.month > 12 ) { Temp.day = 1 ; Temp.month = 1 ; Temp.year = year + 1 ; }

  10. Example else { toHold = day + days ; if ( toHold > daysInThisMonth ) { Temp.day = toHold - daysInThisMonth ; } Temp.year = year ; } }

  11. Example else { Temp.day = days + day ; Temp.month = month ; Temp.year = year ; } return Temp ; }

  12. Unary Operator

  13. i ++ i --

  14. date += 1 ; Same asdate ++ ;

  15. Date operator++ ( ) ;

  16. Unary Member Operator

  17. Example void Date :: operator ++ ( ) { if ( day == daysOfMonth ( day , month , year ) ) { if ( month < 12 ) { day = 1 ; month ++ ; } else { day = 1 ; month = 1 ; year ++ ; } else day ++ ; }

  18. Example Date Date :: operator + ( int days ) { Date Temp ; for ( i = 1 ; i < days ; i ++ ) ++ Temp ; return Temp ; } days = 5

  19. Code Reuse

  20. Comparison Operator < > <= >= ==

  21. bool

  22. bool operator > ( Date d ) ;

  23. Example Date d1 , d2 ; if ( d1 > d2 )

  24. Example Date date ; date + 5 ;

  25. Example 5 + date ;

  26. Interface

More Related