Tuesday, April 28, 2009

Overloading Unary Operator Using + Operator

A plus operator, when used as a unary, takes just one operator. We know that this operator used to add two values. Consider the program we can add hrs and minutes separately using ‘+’ operator.

Example:

header files

class time
{
int hrs, min;
public:
void get(int a,int b)
{
hrs=a;
min=b;
}
time operator +(time ob);
void disp();
void display();
};
time time::operator +(time ob)
{
time t;
t.hrs=hrs+ob.hrs;
t.min=min+ob.min;
return(t);
}
void time::disp()
{
cout<<"\n" <<"Hours=" << hrs <<" " <<"Minutes=" << min << endl;
}
void display()
{
int n1, m;
m=min/60%;
n1=m/60;
hrs=hrs+n1;
cout<<"\n" << hrs <<"hrs" << m <<"mins" << endl;
}
void main()
{
clrscr();
time obj1, obj2, obj3,;
obj1.get(5,0);
obj2.et(7,45);
obj3=obj1+obj2;
obj1.disp();
obj2.disp();
obj3.display();
getch();
}

Output will be

12 hrs 45 mins

No comments:

Post a Comment