将类对象转换为字符串
我有一个类需要我使用两个必需的,教师定义的空函数to_string()
和超载的<运算符将类对象clock_time
转换为字符串。我无法使其工作,我不确定原因。将类对象转换为字符串
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;
}
的问题的关键是to_string
方法使用operator<<
过载clock_time
。不幸的是,operator<<
过载使用to_string
方法。显然,这是行不通的,因为它会永远绕着圈子走。
那么我们如何解决它,使其可以工作?
我们解耦to_string
和operator<<
,以便它们不会互相呼叫。
首先,我们来定义一个伪造的例子clock_time
,因为它缺失了,我们不能在没有它的情况下做所有的千斤顶。
class clock_time
{
int hour;
int minute;
int second;
public:
friend std::ostream& operator<<(std::ostream &out, clock_time c);
}
注operator<<
声明为clock_time
个friend
功能。这允许operator<<
中断封装并使用clock_time
的私有成员。根据clock_time
的定义,这可能不是必要的,但对于这个例子来说,它几乎是整个shebang的关键。
接下来我们实现operator<<
ostream& operator<<(ostream &out, clock_time c)
{
out << c.hour << ":" << c.minute << ":" << c.second;
return out;
}
我选择这个输出格式,因为它是我希望看到一个数字时钟。 “最少惊喜法”说给人们他们期望的东西,你会有更少的错误和不好的感觉。迷惑人们......记得微软从Windows 8上拉开始菜单时发生了什么?或者当可口可乐改变了他们的公式?
我在做operator<<
首先是因为个人喜好。我宁愿在这里做一些咕噜咕噜的工作,因为在我的大脑上比在to_string
出于某种原因更容易。
现在我们准备实施to_string
函数。
string to_string(clock_time c)
{
ostringstream ss;
ss << c;
return ss.str();
}
惊喜!这与OP最初实施它完全一样。由于to_string
和operator<<
已解耦,因此可在to_string
中使用operator<<
。只要其中一个功能对另一个功能起到重要作用,你可以用相反的方式来完成。两者都可以做所有的工作,但为什么?两倍的地方把事情搞砸了。
这很有道理。感谢您的详细解释! –
'to_string'方法对'clock_time'使用'operator user4581301
我得到了运算符重载的工作,但我仍然无法使'to_string'函数工作。任何建议开始? –
@WallaceMogerty'clock_time'的定义是什么? –