Thursday, 14 March 2013

operator overloading time

#include<iostream.h>
#include<conio.h>
class time
{
int hr,mn,sec;
public:
void gettime()
{
cout<<"\nenter time in format of hh:mm:ss ";
cin>>hr>>mn>>sec;
}
void showtime()
{
cout<<"\ncurrent time :"<<hr<<":"<<mn<<":"<<sec;
}
void operator +(int n)
{
sec=sec+n;
if (sec>=60)
{
sec=sec%60;
mn++;
}
if(mn>=60)
{
mn=mn%60;
hr++;
}
if (hr>=24)
{
hr=0;
}
}
void operator <(time &a)
{
if(hr<a.hr)
cout<<"first time is less than second" ;
else
cout<<"first time is greater than second" ;
}
void operator ==(time &a)
{
if(hr==a.hr&&mn==a.mn&&sec==a.sec)
cout<<"two times are equal" ;
else
cout<<"two times are not equal" ;
}
};
void main()
{
clrscr();
time t1,t2,t3;
t1.gettime();
int n=0;
cout<<"enter seconds to be incremented.."   ;
cin>>n;
t1+(n);
t1.showtime();
cout<<"\n1)use of `<' operater";
t2.gettime();
t2.showtime();
t1<t2;
cout<<"\n2)use of `=='operator" ;
t1.gettime();
t1.showtime();
t2.gettime();
t2.showtime();
t1==t2;
getch();
}

operator overloading string

#include
#include
#include
class string
{
private :
char *s;
int len;
public:

string()
{
len=0;
s=0;
}

string(char *c)
{
len= strlen(c);
s = new char[len+1];
strcpy(s,c);
}

void showstring()
{
cout<<"\nstring is : ";
cout< }

friend void operator +(string & p,string & t)
{
string temp;
temp.len=p.len+t.len;
temp.s=new char [temp.len+1];
strcpy(temp.s,p.s);
strcat(temp.s,t.s);
cout<<"\nconcated string : " ;
cout< }

friend void operator ==(string & p,string & t)
{
int m = strlen(p.s);
int n = strlen(t.s);
if(m==n)
cout<<"\ntwo strings are EQUAL";
else
cout<<"\ntwo strins are NOT equal";
}

friend void operator <=(string & p,string & t)
{
int m = strlen(p.s);
int n = strlen(t.s);
if(m<=n)
cout<<"\nstring: "< else
cout<<"\nstring ~ "< }
};
void main()
{
clrscr();
string a("networking"),b;
a.showstring();
b="electronics" ;
b.showstring();
a+b;
a<=b;
a==b;
getch();
}