I am messing around with classes and opertor overloading. I am making a simlpe time class. Basically I would like to be able to create a few Time objects, set their hours and minutes, and then use operator overloading to add them and dislpay the results. This is what I have so far.
Code:
Time.h
#ifndef TIME_H
#define TIME_H
class Time
{
public:
Time();
//~Time();
Time(int hours2, int minutes2);
int getHours() const;
int getMinutes() const;
void setHours(const int hours2);
void setMinutes(const int minutes2);
Time operator+(const Time &t1) const;
void show() const;
private:
int hours, minutes;
};
#endif
Code:
Time.cpp
#include "Time.h"
#include <iostream>
Time::Time()
{
hours = minutes = 0;
}
//Time::~Time()
//{
//}
Time::Time(int hours2, int minutes2)
{
hours = hours2;
minutes = minutes2;
}
int Time::getHours() const
{
return hours;
}
int Time::getMinutes() const
{
return minutes;
}
void Time::setHours(const int hours2)
{
hours = hours2;
}
void Time::setMinutes(const int minutes2)
{
minutes = minutes2;
}
Time Time::operator+(const Time &t1) const
{
Time sum;
sum.minutes = minutes + t1.minutes;
sum.hours = hours + t1.hours + sum.minutes/60;
sum.minutes %=60;
return sum;
}
void Time::show() const
{
std::cout<<"The current time is: "<<hours<<" hours and "<<minutes<<" minutes."<<std::endl;
}
Code:
main.cpp
#include <iostream>
#include "Time.h"
int main(int argc, char *argv[])
{
Time t1(0,0);
Time t2();
Time t3(0,0);
t1.setHours(2);
t1.setMinutes(25);
t1.show();
t2.setHours(3);
t2.setMinutes(65);
t2.show();
t3 = t1 + t2;
t3.show();
std::cin.ignore();
std::cin.get();
return EXIT_SUCCESS;
}
Here are my errors:
Code:
main.cpp: In function `int main(int, char**)':
main.cpp:17: error: request for member `setHours' in `t2', which is of non-class type `Time ()()'
main.cpp:18: error: request for member `setMinutes' in `t2', which is of non-class type `Time ()()'
main.cpp:19: error: request for member `show' in `t2', which is of non-class type `Time ()()'
main.cpp:21: error: no match for 'operator+' in 't1 + t2'
Time.h:13: note: candidates are: Time Time::operator+(const Time&) const
make.exe: *** [main.o] Error 1
Execution terminated
I was trying to create Time objects using two different constructors: one which initializes the hours and minutes to whatever I pass and another that initializes them to 0. If I use the constructor that accepts two arguments it works, but the one that doesn't accept any arguments doesn't work.
Also I have commented out my destructor code. When I leave it in there my program crashes (when using the 2 argument constructor that actually works). Any ideas?
Thanks guys.