'Class member function returning 'time' does not name a type, for functions with class datatype time
I've been trying to figure this out for the past couple of hours. Every page/website I read seems to have a slightly different issue, and I can't apply what it's saying or don't fully understand what it's saying and can't apply it. I unfortunately feel like I can't do anything else except post this, I'm sorry if it's been asked a million times before.
Anyways, below is my code and the compiler errors. The program should have two classes that use the class name datatype, sum and an operator overload, however this is the root of my errors.
I've tried everything except moving the class to a header file, is this necessary?
using namespace std;
#include <iostream>
class time {
private:
int hour;
int minute;
public:
// constructor
time();
// mutator functions
void settime(int, int);
time sum(time); // sums two time objects
// accessor functions
void showtime();
// overloaded operations
time operator + (const time &);
};
int main() {
// declare time objects
time timeA, timeB, timeC;
int tempHour, tempMinute;
cout << "Enter time 1 hours: ";
cin >> tempHour;
cout << "Enter time 1 minutes: ";
cin >> tempMinute;
timeA.settime(tempHour, tempMinute); // initialize timeA object
cout << "Enter time 2 hours: ";
cin >> tempHour;
cout << "Enter time 2 minutes: ";
cin >> tempMinute;
timeB.settime(tempHour, tempMinute); // initialize timeB object
// sum the times
timeC = timeA.sum(timeB);
cout << "The sum of the two times is: " << timeC.showtime() << endl;
return 0;
}
// define time member functions
// cunstructor func
time::time() {
hour = 0;
minute = 0;
}
void time::settime(int newHour, int newMinute) {
hour = newHour;
minute = newMinute;
}
void time::showtime() {
cout << time::hour << ":" << time::minute << endl;
}
time time::sum(time time2) {
time newTime;
int newHour, newMinute;
newHour = hour + time2.hour;
newMinute = minute + time2.minute;
newTime.settime(newHour, newMinute);
return newTime;
}
// this defines the addition operator for time objects
time time::operator + (const time &right) {
time temp;
temp.minute = minute + right.minute;
temp.hour = hour + right.hour;
if (temp.minute > 59) {
temp.hour += temp.minute / 60; // leave as int so hour is always lowest number
temp.minute = temp.minute % 60;
}
return temp;
}
I apologize for posting the whole code, but I'm not exactly sure where the error is. When compiling the above, it returns: 'error: 'time does not name a type' for the definition of the member functions at the bottom for operator and sum.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
