Thursday, September 13, 2012

Operator Overloading in C++ Programming Hr Min Sec Example

Operator Overloading in C++ Programming Hr Min Sec Example

Question:
Create a class Time with members hr, min and sec. Write all three
constructors, destructor, and make one static member to count the objects of
class.Overload the following operators :
>>,<<,= =,=,+,++,--

Solutions:

/* Program for Operator Overloading */

#include<iostream>
using namespace std;

static int c=0;

class Time
{
public:
int hr,m,s;

Time()
{
hr=0;m=0;s=0;
//cout<<"\nDefault Constructor Called!"<<endl;
c++;
}
Time(int thr,int tm,int ts)
{
hr=thr;
m=tm;
s=ts;
//cout<<"\nParameterized Constructor!"<<endl;
c++;
}

~Time()
{

}
Time operator+(Time);
void operator++();
void operator--();
void operator>>(Time);
void operator<<(Time);
void operator==(Time);
void operator=(Time);
};

Time Time::operator+(Time op)
{Time temp;
temp.s=s+op.s;
if(temp.s>=60)
{
m++;
temp.s=temp.s%60;
}
temp.m=m+op.m;
if(temp.m>=60)
{
hr++;
temp.m=temp.m%60;
}
temp.hr=hr+op.hr;
return temp;
}

void Time::operator>>(Time op)
{cout<<"Enter the Values for Hr Min Sec"<<endl;
cin>>hr>>m>>s;

}

void Time::operator<<(Time op)
{
cout<<"\nTime is:"<<hr<<"hr "<<m<<"m "<<s<<"s "<<endl;
}

void Time::operator==(Time op)
{
if(hr==op.hr && m==op.m && s==op.s)
{
 cout<<"Given Times are Same"<<endl;
}
else
 cout<<"Gives Times are Different!"<<endl;
}

void Time::operator=(Time op)
{
hr=op.hr;
m=op.m;
s=op.s;
}

void Time::operator++()
{
++s;
if(s>=60)
{
m++;
s=s%60;
}
if(m>=60)
{
hr++;
m=m%60;
}

}

void Time::operator--()
{
s--;
if (s<0)
{
s=59;
m--;
}
if (m<0)
{
m=59;
hr--;
}

}


int main()
{
Time hr1(2,30,59);Time hr2(1,20,21);
Time s1,s2,s3;
Time addhr=hr1+hr2;
cout<<"\nThe Addition is:"<<addhr.hr<<"hr "<<addhr.m<<"m "<<addhr.s<<"s "<<endl;
s1>>hr1;
s2>>hr1;
s3=s1+s2;
s3<<hr1;
//s3<<;
++s3;
s3<<hr1;
hr1>>hr1;
--hr1;
hr1<<hr1;
cout<<"\nTotal Object Created:"<<c<<endl;
return 0;
}

0 comments:

Post a Comment