为了覆盖toString()函数,我正在尝试扩展QTime类。
-EDIT-我真正需要的是一种简洁的方式,只显示十分之一秒,而不是毫秒。我目前的解决方案类似于:
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运算符=以解决此问题?
发布于 2014-01-16 19:39:14
如何重写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;
}
};发布于 2014-01-16 22:01:09
从QTime派生出来的方法是完全错误的。如果您需要不同的时间格式,只需编写一个独立的函数:
QString myTimeFormat(const QTime & time) {
const QString str = time.toString("ss.zzz");
return str.left(str.size() - 2);
}面向对象不是通用的锤子。有时,一个普通的旧函数就可以做得很好。
发布于 2014-01-16 23:14:28
子类化和重写在这里是没有意义的,简单的函数就可以了。
我会这样做(作为静态类方法或全局函数)。
QString myTimeFormat(const QTime & time) {
QString result = QString("%1.%2").arg(time.second())
.arg((time.msec()+50)/100);
return result;
}https://stackoverflow.com/questions/21160351
复制相似问题