【发布时间】: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')
问题在于FooTime 是QTime,但QTime 不是FooTime。
如何覆盖FooTime 运算符= 以解决此问题?
【问题讨论】:
-
为什么需要重写toString,只使用其中一种格式化函数
-
因为我想使用默认未提供的不同格式。
-
你不能覆盖
QTime::toString()函数,因为它不是一个虚函数。 -
@vahancho Ops,这是个问题。但是我可以添加一个新的
myToString()函数,对吧? -
@ital,是的,你可以,但是为了什么?:) 请解释一下你需要什么特殊格式,这是 QTime 类无法实现的?
标签: c++ qt inheritance overriding