What is operator+ (MyTime)?

All QuestionsCategory: Cpp LanguageWhat is operator+ (MyTime)?
Anonymous asked 3 years ago
1 Answers
Anonymous answered 3 years ago

While overloading binary operator as a member function, the first operand invokes the member function and the second one is passed to the member function.
For eg:- when t1+t2 is requested, t1 invokes operator+ and t2 will be passed to a member function.

MyTime t3;
t3=t1+t2;     //t3=t1.operator+(t2);

To support the above operation, we can add the following member function to our class

MyTime operator+(const MyTime& ref) 
{
int th,tm; th=this->hh+ref.hh; tm=this->mm+ref.mm; return MyTime(th,tm); //temporaray unnamed objects }


Complete Code



class MyTime {
int hh;
int mm;

public:
MyTime():hh(0),mm(0) { }
MyTime(int h, int m) : hh(h), mm(m) {}
MyTime(const MyTime &ref) : hh(ref.hh), mm(ref.mm) {}
MyTime operator+(const MyTime &ref) {
int tmins = mm + ref.mm; //TODO:tmins > 60
int thrs = hh + ref.hh;
// MyTime tmp(thhrs, tmins);
//return tmp;
return MyTime(thrs, tmins);
}
void display() const { std::cout << hh << ":" << mm << "\n"; }

};
int main() {
MyTime t1(10,20);
MyTime t2(1,15);
MyTime t3;
t3 = t1 + t2; // t1.operator+(t2)
t3.display();

return 0;
}