c – 必须使用’.*’或’ – > *’在’lessThan(…)’中调用指向成员的函数,例如'(… – > * lessThan)(…)’

我试图基于QDateTime对我的QList进行排序,但是我收到以下错误:

must use '.*' or '->*' to call pointer-to-member function in 'lessThan (...)', e.g. '(... ->* lessThan) (...)'
 if (lessThan(*end, *start))
                          ^

排序功能:

bool sortRecord(Record left, Record right){
    return left.getArrival().getDate() < right.getArrival().getDate();
}

函数调用如下:

qSort(recordList.begin(), recordList.end(), sortRecord);

到达记录的吸气剂和制定者:

void Record::setArrival(Arrival arrival){
    this->arrival = arrival;
}
Arrival Record::getArrival(){
    return this->arrival;
}

到货中的getDate()函数:

QDateTime Arrival::getDate(){
    QDateTime qDateTime;

    QDate qDate;
    qDate.setDate(date.getDateYear(), date.getDateMonth(), date.getDateDay());
    qDateTime.setDate(qDate);

    vector<string> timeS = splitTime(time.getTimeFrom());

    QTime qTime;
    qTime.setHMS(stoi(timeS[0]), stoi(timeS[1]), 0);
    qDateTime.setTime(qTime);

    return qDateTime;
}

我做错了什么?

谢谢!

解决方法:

问题出在这里:

qSort(recordList.begin(), recordList.end(), sortRecord);
                                            ^^^^^^^^^^

您不能使用非静态成员函数作为sort函数,因为需要在某个对象上调用非静态成员函数(以提供this指针).你不能像正常函数一样调用成员函数,这就是编译器错误的含义.如果您已经阅读了整个错误消息,而不仅仅是第一行,那么它会告诉您它来自上面的行.

使sortRecord函数成为非成员函数,或使其成为静态成员函数.

为什么它仍然是会员功能?它不会访问* this,或使用任何私有成员……这闻起来像是面向对象的糟糕风格,而不是我们在C中做事的方式(参见例如How non-member functions increase encapsulation).

另外,为什么sortRecord函数复制其参数而不是使用引用? (见https://isocpp.org/wiki/faq/references#call-by-reference)

如果你想把所有东西都写成成员函数并且有传递引用语义,那么使用Java而不是C语言.否则,停止在C中编写Java代码.

上一篇:halcon-for循环


下一篇:Html+Css+Js(while 结构语句)打印0-100之间7的倍数、打印0-100之间偶数、打印0-100之间所有奇数的和。