首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从QTime继承,以便自定义时间格式

从QTime继承,以便自定义时间格式
EN

Stack Overflow用户
提问于 2014-01-16 19:20:52
回答 3查看 229关注 0票数 0

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

-EDIT-我真正需要的是一种简洁的方式,只显示十分之一秒,而不是毫秒。我目前的解决方案类似于:

代码语言:javascript
复制
QString original = qtime.toString("ss.zzz");
QString tenths = original.left(original.size() - 2);  // discards hundredths and msecs

我想要做的是:

代码语言:javascript
复制
QString tenths = fooTime.myToString("ss.x");  // discards hundredths and msecs

-编辑

这个类如下所示:

代码语言:javascript
复制
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在这些函数中有一个棘手的行为:

代码语言:javascript
复制
class QTime
{
    ...
    QTime addMSecs(int ms) const;
    QTime addSecs(int s) const;
    ...
}

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

代码语言:javascript
复制
...
FooTime t(0, 0);
t = t.addMSecs(1000);  // compile error, no match for 'operator=' (operand types are 'FooTime' and 'QTime')

问题是FooTimeQTime,而QTime不是FooTime

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

EN

回答 3

Stack Overflow用户

发布于 2014-01-16 19:39:14

如何重写FooTime运算符=以解决此问题?

这应该足够了:

代码语言:javascript
复制
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;
    }
};
票数 1
EN

Stack Overflow用户

发布于 2014-01-16 22:01:09

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

代码语言:javascript
复制
QString myTimeFormat(const QTime & time) {
  const QString str = time.toString("ss.zzz");
  return str.left(str.size() - 2);
}

面向对象不是通用的锤子。有时,一个普通的旧函数就可以做得很好。

票数 1
EN

Stack Overflow用户

发布于 2014-01-16 23:14:28

子类化和重写在这里是没有意义的,简单的函数就可以了。

我会这样做(作为静态类方法或全局函数)。

代码语言:javascript
复制
QString myTimeFormat(const QTime & time) {
  QString result = QString("%1.%2").arg(time.second())
                                   .arg((time.msec()+50)/100);
  return result;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21160351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档