Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

qt

qlist

qsort

I am trying to sort my QList based on a QDateTime but I get the following error:

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

Sort function:

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

Function is called like this:

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

Getter and setter of arrival in Record:

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

getDate() function in Arrival:

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;
}

What is it that I do wrong?

Thanks!

like image 737
Jelmer Visser Avatar asked Nov 25 '15 09:11

Jelmer Visser


2 Answers

The problem is here:

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

You cannot use a non-static member function as the sort function, because a non-static member function needs to be called on some object (to provide the this pointer). You can't just call member function like a normal function, which is what the compiler error means. If you'd read the whole error message, not just the first line, then it would have told you that it comes from the line above.

Either make the sortRecord function a non-member function, or make it a static member function.

Why is it a member function anyway? It doesn't access *this, or use any private members ... this smells like bad object oriented style, that's not how we do things in C++ (see e.g. How non-member functions increase encapsulation).

Also why does your sortRecord function copy its arguments instead of using references? (See https://isocpp.org/wiki/faq/references#call-by-reference)

If you want to write everything as a member function and have pass-by-reference semantics then use Java, not C++. Otherwise, stop writing Java code in C++.

like image 186
Jonathan Wakely Avatar answered Nov 15 '22 00:11

Jonathan Wakely


Try this function for sorting.

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

And also make sure that getArrival() and getDate() are const methods.

like image 37
sanjay Avatar answered Nov 14 '22 23:11

sanjay