For my PPP2 book, I need to implement a Date class which has an enum class Month for the months. I can't output the months that easily with operator<<, as the compiler keeps giving me the error that no operator<< exists for Month. I tried to overload it like this:
1 2 3 4
ostream& operator<<(ostream &os, const Month &m)
{
return os << m;
}
But this gave me the following warning:
'Chrono::operator<<': recursive on all control paths, function will cause runtime stack overflow
And of course, when I wrote the full program and tried to output a Date, it crashed with a stack overflow error.
How do I fix this? [Note: In the full code, the Date class and the Month enum class are part of a namespace called Chrono.]
Your operator<< is recursive so if it was called it would never end. It would just keep calling itself until the end of time (or until the program runs out of stack space).
What you probably should do instead is to use a switch statement or a chain of if statements to output the name of the month for each enum value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
ostream& operator<<(ostream &os, Month m)
{
switch (m)
{
case Month::january:
os << "January";
break;
case Month::february:
os << "February";
break;
...
}
return os;
}
I'm doing a drill right now that says to use earlier versions of Date and work my up to the later versions. The earliest version is just a simple struct and the latest one is a class. One of the earlier ones didn't have the getter functions in the Date class as const. Apparently, when the getters aren't const, the compiler doesn't know if we'll modify the const stuff in the operator functions so it doesn't let us do it, not even non-const. Once I made the arguments that aren't being modified const, it worked.
Now I'm having trouble overloading operator+=, though. Here's what I have right now: