1

I need to make an adapter for QTimeEdit to use it with time_t in:

  1. constructor QTimeEdit(time_t)
  2. void setTime(time_t)
  3. time_t time() I did 1. and its working.
class QTimeEditAdapter: public QTimeEdit {
public:
    QTimeEditAdapter(time_t t) {
        tm1 = t;
        tm *ltm = localtime(&tm1);
        int hours = ltm->tm_hour;
        int min = ltm->tm_min;
        this->setTime(QTime(hours,min));
    }
private:
    time_t tm1;
};
int main(int argc, char *argv[])
{
    time_t tm1;
    tm1 = time(NULL);

    //other qt widgets code

    QTimeEdit* timeEdit = new QTimeEditAdapter(tm1);

    //more other qt widgets code

But if I'm adapting setTime by adding

void setTime(time_t t1)

to the class its redefines setTime and I'm getting mistakes from both constructor and method setTime. I didn't found any other method to set time in QTimeEdit but I guess there must be a way better than my

4

1 回答 1

1

与基类成员同名的派生类成员隐藏了对基类成员的直接使用 -- C++ Primer (5th Edition), Pg 618

基于参数列表的函数重载在派生类和基类之间是不可能的。如果您拨打this->setTime(QTime(hours,min));where thisis a之类的电话,则重载决议中只会考虑QTimeEditAdapter您的 new 。QTimeEditAdapter::setTime(time_t)这会导致编译错误。

要解决此问题,您可以直接在构造函数中引用基类:

QTimeEditAdapter::setTime(QTime(hours,min));

但这不会帮助您的适配器的其他用户访问原始setTime.

另一种解决方法是添加以下内容:

void setTime(QTime qt)
{
        QTimeEdit::setTime(qt);
}

这解决了问题,但现在您负责枚举基类定义的所有(现在或将来)可能的重载。

为了避免这些棘手的问题,最好为您的方法选择一个不同的方法名称QTimeEditAdapter::setTime(time_t)

于 2020-04-12T03:53:45.597 回答