gpt4 book ai didi

c++ - 继承QTime,自定义时间格式

转载 作者:行者123 更新时间:2023-11-28 00:35:19 25 4
gpt4 key购买 nike

我正在尝试扩展 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 运算符 = 以解决此问题?

最佳答案

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

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

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

关于c++ - 继承QTime,自定义时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21160351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com