Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 26

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 ;
}
Date operator + ( int i ) ;
Example
Date Date :: operator + ( int days )
{
Date Temp ;
int toHold ;
int daysInThisMonth = 0 ;
daysInThisMonth = daysInMonth ( month ) ;
toHold = days ;
Example
if ( ( day + days ) >= daysInThisMonth )
if ( ( day + days ) >= daysInThisMonth )
{
Temp.month = month + 1 ;
if ( Temp.month > 12 )
{
Temp.day = 1 ;
Temp.month = 1 ;
Temp.year = year + 1 ;
}
else
Example
{
toHold = day + days ;
if ( toHold > daysInThisMonth )
{
Temp.day = toHold - daysInThisMonth ;
}
Temp.year = year ;
}
}
else
Example
{
Temp.day = days + day ;
Temp.month = month ;
Temp.year = year ;
}
return Temp ;
}
Unary
Operator
i ++
i --
date += 1 ;
Same as
date ++ ;
Date operator++ ( ) ;
Unary Member
Operator
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 )
{
days = 5
Date Temp ;
for ( i = 1 ; i < days ; i ++ )
++ Temp ;
return Temp ;
}
Code
Reuse
Comparison Operator
<
>
<=
>=
==
bool
bool operator > ( Date d ) ;
Example

Date d1 , d2 ;
if ( d1 > d2 )
Example
Date date ;
date + 5 ;
Example

5 + date ;
Interface

You might also like