I have an assignment for a class that requires me to convert a class object, clock_time
, to a string using two required, instructor-defined empty functions: to_string()
and an overloaded << operator. I am not able to get it to work and I am unsure why.
clock_time::clock_time(int h, int m, int s)
{
set_time(h, m, s);
}
void clock_time::set_time(int h, int m, int s)
{
_seconds = h * 3600 + m * 60 + s;
}
string to_string(clock_time c)
{
ostringstream ss;
ss << c;
return ss.str();
}
ostream& operator<<(ostream &out, clock_time c)
{
out << to_string(c);
return out;
}
The crux of the problem is the to_string
method uses the operator<<
overload for clock_time
. Unfortunately, The operator<<
overload uses the to_string
method. Obviously this can't work because it's going to go around in circles forever.
So how do we fix it up so that it can work?
We uncouple to_string
and operator<<
so that they don't call each other.
First off, let's define a bogus example clock_time
because it's missing and we can't do jack all without it.
class clock_time
{
int hour;
int minute;
int second;
public:
friend std::ostream& operator<<(std::ostream &out, clock_time c);
}
Note the declaration of operator<<
as a friend
function of clock_time
s. This allows operator<<
to break encapsulation and use the private members of clock_time
. This might not be necessary depending on how clock_time
has been defined, but for this example, it's pretty much the key to the whole shebang.
Next we implement operator<<
ostream& operator<<(ostream &out, clock_time c)
{
out << c.hour << ":" << c.minute << ":" << c.second;
return out;
}
I've chosen this output format because it's what I expect to see on a digital clock. The Law of Least Surprise says give people what they expect and you'll have fewer bugs and bad feelings. Confuse people and... Well remember what happened with when Microsoft pulled the start menu from Windows 8? Or when Coke changed their formula?
I'm doing operator<<
first because of personal preference. I'd rather do the grunt work here because it's easier on my brain than doing it in to_string
for some reason.
Now we're ready to implement the to_string
function.
string to_string(clock_time c)
{
ostringstream ss;
ss << c;
return ss.str();
}
Surprise! It's exactly the same as OP originally implemented it. Because to_string
and operator<<
have been uncoupled, operator<<
is available for use in to_string
. You could do it the other way around, so long as one of the functions does the heavy lifting for the other. Both could also do all of the work, but why? Twice as many places to screw things up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With