How to add two operator overloading functions (- and ==) ?

Hello, sorry i'm currently new in programming, and i'm currently learning about operator overloading.
So, i made a time program, like this :

#include <iostream>
using namespace std;

class Time {
private:
int hour;
int minute;
int second;
public:
Time()
{
hour=0;
minute=0;
second=0;
}
Time(int h, int m, int s)
{
hour=h;
minute=m;
second=s;
}
void DisplayTime()
{
cout<<"Time : "<<hour<<":"<<minute<<":"<<second<<endl;
}
void ChangeHour(int h)
{
hour=h;
}
void ChangeMinute(int m)
{
minute=m;
}
void ChangeSecond(int s)
{
second=s;
}



Time operator+ (const Time& t)
{
int hasil_hour;
int hasil_minute;
int hasil_second;
Time hasil;

hasil_hour = hour + t.hour;
hasil_minute = minute + t.minute;
hasil_second = second + t.second;



if (hasil_second>60)
{
hasil_second = hasil_second-60;
hasil_minute= hasil_minute+1;
}
if (hasil_minute>60)
{
hasil_minute = hasil_minute-60;
hasil_hour= hasil_hour+1;
}


hasil.hour = hasil_hour;
hasil.minute = hasil_minute;
hasil.second = hasil_second;

return hasil;
}
};

int main ()
{
Time T1(1,30,50);
Time T2(1,15,58);
Time T3;
T3 = T1+T2;
T3.DisplayTime();
}

I was wondering how i'm gonna add 2 new operator (- and ==) into the code?
+ and - are virtually identical. if you wrote +, what is giving you trouble with the -?
You can simplify operator+() somewhat.
- Use hasil directly instead of having separate hasil_second, hasil_minute and hasil_hour variables.
- Use the ++ and += operators:
x++ means x = x + 1.
x += y means x = x + y

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    Time operator+(const Time & t)
    {
        Time hasil(t);          // make a copy of t

        // Add my values to hasil. x += y is the same as x = x + y
        hasil.hour += hour;
        hasil.second += second;
        hasil.minute += minute;

        // Now normalize the values
        if (hasil.second > 60) {
            hasil.second -= 60;
            hasil.minute++;     // x++ is the same as x = x + 1
        }
        if (hasil.minute > 60) {
            hasil.minute -= 60;
            hasil.hour++;
        }

        return hasil;
    }
};
The operator+ does not have to be a member of Time, if you create member operator+= and use it in the stand-alone operator+ :
1
2
3
4
5
Time operator+ ( Time lhs, const Time& rhs )
{
  lhs += rhs;
  return lhs;
}


Of course, writing operator+= is a logical puzzle too:
1
2
3
4
Time& Time::operator+= ( const Time& rhs )
{
  // ???
}

Topic archived. No new replies allowed.