Example:16
Declare a class named “distance” with attributes as km, m, cm and mm. Take input for two objects calculate and print their sum using overloaded binary operator “+”.
code
Output:
Example:17
Declare a class named “distance” with attributes as km, m, cm and mm. Take input for two objects calculate and print their sum using overloaded binary operator “+” with friend function.
code
Output:
Example:18
Declare a class named “time” with attributes as hh, mm, ss. Take input for two objects calculate and print their sum using overloaded binary operator “+”.
//Add two time objects //using "+" overloaded operator #include<iostream> #include<conio.h> using namespace std; class time { private: int h,m,s; public: void read(); void show(); time operator+(time t1); }; void time::read() { cout<<"enter h,m and s "; cin>>h>>m>>s; } void time::show() { cout<<h<<" : "<<m<<" : "<<s<<endl; } time time::operator+(time t1) { time t; t.h=h+t1.h; t.m=m+t1.m; t.s=s+t1.s; if(t.s>=60) { t.m=t.m+t.s/60; t.s=t.s%60; } if(t.m>=60) { t.h=t.h+t.m/60; t.m=t.m%60; } return(t); } int main() { time e1,e2,e3; e1.read();e2.read(); e1.show();e2.show(); e3=e1+e2;//e3=e1.operator(e2); e3.show(); getch(); return(0); }
Output:
enter h,m and s 3 6 9
enter h,m and s 4 5 8
3 : 6 : 9
4 : 5 : 8
7 : 11 : 17