【问题标题】:Convert Class Object to String将类对象转换为字符串
【发布时间】:2017-02-07 05:56:57
【问题描述】:

我有一个类的任务,要求我使用两个必需的、教师定义的空函数将一个类对象 clock_time 转换为一个字符串:to_string() 和一个重载的

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 方法对clock_time 使用operator&lt;&lt; 重载。 operator&lt;&lt; 使用 to_string 方法。有点鸡和蛋的事情发生在这里,我的朋友。
  • 我让运算符重载工作,但我仍然无法让to_string 函数工作。有什么建议可以开始吗?
  • @WallaceMogerty clock_time的定义是什么?
  • @AmiTavory clock_time 在给定小时、分钟和秒的 int 值的情况下返回以秒为单位的时间。我已经在类中实现了获取小时、分钟等的方法。
  • 最好在问题中添加clock_time。没有它,除了猜测之外,很难做更多的事情。

标签: c++ class overloading


【解决方案1】:

问题的症结在于to_string 方法对clock_time 使用了operator&lt;&lt; 重载。不幸的是,operator&lt;&lt; 重载使用了to_string 方法。显然这是行不通的,因为它会永远循环下去。

那么我们如何修复它以使其正常工作?

我们将to_stringoperator&lt;&lt; 解耦,这样它们就不会互相调用。

首先,让我们定义一个虚假示例 clock_time,因为它丢失了,没有它我们就无法完成所有操作。

class clock_time
{
    int hour;
    int minute;
    int second;

public:
    friend std::ostream& operator<<(std::ostream &out, clock_time c);
}

注意operator&lt;&lt; 声明为clock_times 的friend 函数。这允许operator&lt;&lt; 打破封装并使用clock_time 的私有成员。这可能不是必需的,具体取决于 clock_time 的定义方式,但对于这个示例,它几乎是整个 shebang 的关键。

接下来我们实现operator&lt;&lt;

ostream& operator<<(ostream &out, clock_time c)
{
    out << c.hour << ":" << c.minute << ":" << c.second;
    return out;
}

我选择了这种输出格式,因为这是我希望在数字时钟上看到的。最小惊喜法则说,给人们他们期望的东西,你就会有更少的错误和不好的感觉。让人们感到困惑......好吧,还记得微软从 Windows 8 中删除开始菜单时发生了什么吗?或者当可口可乐改变他们的配方时?

由于个人喜好,我先做operator&lt;&lt;。我宁愿在这里做繁重的工作,因为出于某种原因,它比在to_string 中做更容易。

现在我们准备好实现to_string 函数了。

string to_string(clock_time c)
{
    ostringstream ss;
    ss << c;
    return ss.str();
}

惊喜!它与 OP 最初实现的完全一样。因为to_stringoperator&lt;&lt; 已经解耦,所以operator&lt;&lt; 可以在to_string 中使用。你可以反过来做,只要其中一个功能为另一个功能完成繁重的工作。两者都可以完成所有工作,但为什么呢?搞砸的地方是原来的两倍。

【讨论】:

  • 这很有意义。感谢您的详细解释!
猜你喜欢
  • 2011-09-30
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
  • 2018-09-12
  • 2018-12-08
  • 2014-01-14
  • 2011-08-02
相关资源
最近更新 更多