|
Create 2 files for this program |
|
class Time used to demonstrate operator overloading (time.h) |
| class Time{ protected : int sec; int min; int hour; public: Time(){sec=0;min=0;hour=0;} Time(int s,int m,int h) { sec=s; min=m; hour=h; } void setsec(int s){sec=s;} void setmin(int m){min=m;} void sethour(int h){hour=h;} int getsec(){return sec;} int getmin(){return min;} int gethour(){return hour;} void showTime(){cout<< hour <<"h "<< min <<"m "<<sec<<"s "<<"\n";} //Overloaded operator function to add a time to this object's time Time operator+(Time t2) { Time temp; temp.setsec(sec + t2.getsec()); temp.setmin(min + t2.getmin()); temp.sethour(hour + t2.gethour()); return temp; } //Overloaded operator function to compare a time with this object's time int operator==(Time t2) { if( sec==t2.getsec() && min==t2.getmin() && hour==t2.gethour()) return 1; else return 0; } //Overloaded operator function to increment this object's time by one second void operator++() { sec++; if(sec==60){sec=0; min++;} if(min==60){min=0 ;hour++;} if(hour==24){hour=0;} }};//end class Time |
|
Adding 2 times |
| #include<iostream.h> #include "time.h" void main(){ Time T1(10,10,10) ,T2(15,15,15) ,T3(30,30,30),T4; // Adding 2 objects T1 + T2 and storing the result in o4 T4= T1 + T2; cout<<"T1 : "; T1.showTime(); cout<<"T2 : "; T2.showTime(); cout<<"T3 : "; T3.showTime(); cout<<"\nT1 + T2 = "; T4.showTime(); //Comparing the 3 objects T1,T2 and T3 if(T1==T2) cout<<"T1 and T2 are equal \n"; else cout<<"\n\nT1 and T2 are not equal \n"; if(T1==T3) cout<<"T1 and T3 are equal \n"; else cout<<"T1 and T3 are not equal \n"; if(T2==T3) cout<<"T2 and T3 are equal \n"; else cout<<"T2 and T3 are not equal \n"; // The seconds for T1 are incremented ++T1; cout<<"\n T1 after incrementing it is "<< T1.gethour() << " : "<< T1.getmin() <<" : "<<T1.getsec()<<"\n"; } |