Thanks for all the replies. I've come up with a snag though and I have absolutely no idea why. I'm doing exercises on Operator Overloading (changing the operators function for classes) and have no idea why my time time::operator - (time t2) Isn't working correctly. All others work fine. It is not subtracting the first time from the second, but if I reverse it (fTemp = fTime2 - fTime1) it works fine... here's the snipped and give me your thoughts! (Even on coding style if I'm learning bad habbits). Cheers!
// Exercise 3
#include <iostream>
using namespace std;
class time
{
private:
int hours;
int minutes;
int seconds;
public:
time():hours(0), minutes(0), seconds(0)
{}
time (int h, int m, int s):hours(h), minutes(m), seconds(s)
{}
void timeDisplay() const;
time operator + (time t2);
void operator ++();
void operator --();
time operator - (time t2);
time operator * (time t2);
};
time time::operator -(time t2)
{
hours = hours - t2.hours;
minutes = minutes - t2.minutes;
seconds = seconds - t2.seconds;
while(seconds < 0)
{
seconds += 60;
--minutes;
}
while(minutes < 0)
{
minutes += 60;
--hours;
}
return time(hours, minutes, seconds);
}
time time::operator *(time t2)
{
hours *= t2.hours;
minutes *= t2.minutes;
seconds *= t2.seconds;
while(seconds > 60)
{
seconds -= 60;
minutes++;
}
while(minutes > 60)
{
minutes-= 60;
hours++;
}
return time(hours, minutes, seconds);
}
void time::operator --()
{
--hours;
--minutes;
--seconds;
if(hours<0)
{
hours = 0;
minutes += 60;
}
if(minutes > 60)
{
minutes -= 60;
++hours;
}
if(seconds > 60)
{
seconds -= 60;
++minutes;
}
}
void time::operator ++()
{
++hours;
++minutes;
++seconds;
if(seconds > 60)
{
seconds -= 60;
++minutes;
}
if(minutes > 60)
{
minutes -+60;
++hours;
}
}
void time::timeDisplay() const
{
cout << hours << ':' << minutes << ':' << seconds;
cout << endl;
}
time time::operator +(time t2)
{
hours = hours + t2.hours;
minutes = minutes + t2.minutes;
seconds = seconds + t2.seconds;
while (seconds > 60)
{
seconds -= 60;
minutes++;
}
while (minutes > 60)
{
minutes -= 60;
hours++;
}
return time(hours, minutes, seconds);
}
int main()
{
time fTime1(12, 42, 56); // Initialize some times
time fTime2(1, 23, 42) ;
time fTemp;
fTemp = fTime1 + fTime2;
fTemp.timeDisplay();
++fTemp;
fTemp.timeDisplay();
--fTemp;
fTemp.timeDisplay();
fTemp = fTime1 - fTime2;
fTemp.timeDisplay();
fTemp = fTime1 * fTime2;
fTemp.timeDisplay();
return 0;
}