【问题标题】:Inherit from QTime in order to customize time format从 QTime 继承以自定义时间格式
【发布时间】:2014-01-16 11:20:51
【问题描述】:

我正在尝试扩展 QTime 类以覆盖 toString() 函数。

----编辑----- 我真正需要的是一种只显示十分之一/百分之一秒而不是毫秒的简洁方式。我目前的解决方案是这样的:

QString original = qtime.toString("ss.zzz");
QString tenths = original.left(original.size() - 2);  // discards hundredths and msecs

我想做的是这样的:

QString tenths = fooTime.myToString("ss.x");  // discards hundredths and msecs

---编辑----

这个类如下所示:

class FooTime : public QTime
{
public:
    FooTime()
    {}

    FooTime(int h, int m, int s = 0, int ms = 0)
    : QTime(h, m, s, ms)
    {}

    QString toString(const QString& format) const // the function I need to override
    {
        return format + " foo";
    }

    FooTime& operator=(const FooTime& t)
    {
        // ??? see below.
    }
};

不幸的是,QTime 在这些函数中有一个棘手的行为:

class QTime
{
    ...
    QTime addMSecs(int ms) const;
    QTime addSecs(int s) const;
    ...
}

所以实际上我不能写下面的代码:

...
FooTime t(0, 0);
t = t.addMSecs(1000);  // compile error, no match for 'operator=' (operand types are 'FooTime' and 'QTime')

问题在于FooTimeQTime,但QTime 不是FooTime

如何覆盖FooTime 运算符= 以解决此问题?

【问题讨论】:

  • 为什么需要重写toString,只使用其中一种格式化函数
  • 因为我想使用默认未提供的不同格式。
  • 你不能覆盖QTime::toString()函数,因为它不是一个虚函数。
  • @vahancho Ops,这是个问题。但是我可以添加一个新的myToString() 函数,对吧?
  • @ital,是的,你可以,但是为了什么?:) 请解释一下你需要什么特殊格式,这是 QTime 类无法实现的?

标签: c++ qt inheritance overriding


【解决方案1】:

QTime 的派生是完全错误的方法。如果您需要不同的时间格式,只需编写一个独立的函数:

QString myTimeFormat(const QTime & time) {
  const QString str = time.toString("ss.zzz");
  return str.left(str.size() - 2);
}

面向对象不是万能的锤子。有时一个普通的旧函数就可以了。

【讨论】:

    【解决方案2】:

    子类化和覆盖在这里没有意义,简单的函数就可以完成这项工作。
    我会这样做(作为静态类方法或全局函数)。

    QString myTimeFormat(const QTime & time) {
      QString result = QString("%1.%2").arg(time.second())
                                       .arg((time.msec()+50)/100);
      return result;
    }
    

    【讨论】:

      【解决方案3】:

      如何覆盖 FooTime 运算符 = 以解决此问题 有问题吗?

      这就足够了:

      class FooTime : public QTime
      {
      public:
          FooTime& operator=(const QTime& t)
          {
              QTime::operator=(t);
              /* Assign other things if there is a need, manage memory etc,
                 but it seems that there are no members in FooTime,
                 just functions, so it's all. */
              return *this;
          }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多