为什么qSort()不起作用?

Rob*_*sen 3 qt qt4

好的,我正在尝试对我自己的TvShow类列表进行排序,以按用户决定的顺序显示TvShows列表.这是我在阅读qSort()上的文档后到目前为止所提出的.

bool MainWindow::compareShowsByName(TvShow* showA, TvShow* showB)
{
    return showA->getShowName() < showB->getShowName();
}

QList<TvShow*> MainWindow::orderShowsByName()
{
    QList<TvShow*> orderedShowList = appSettings.TvShows;
    qSort(orderedShowList.begin(), orderedShowList.end(), compareShowsByName);
    return orderedShowList;
}
Run Code Online (Sandbox Code Playgroud)

当然,这会失败并出现以下错误:

../EpisodeNext/mainwindow.cpp: In member function 'QList<TvShow*> MainWindow::orderShowsByName()':
../EpisodeNext/mainwindow.cpp:192: error: no matching function for call to 'qSort(QList<TvShow*>::iterator, QList<TvShow*>::iterator, <unresolved overloaded function type>)'
../../QtSDK/Simulator/Qt/gcc/include/QtCore/qalgorithms.h:184: note: candidates are: void qSort(RandomAccessIterator, RandomAccessIterator, LessThan) [with RandomAccessIterator = QList<TvShow*>::iterator, LessThan = bool (MainWindow::*)(TvShow*, TvShow*)]
../EpisodeNext/mainwindow.cpp: In member function 'QList<TvShow*> MainWindow::orderShowsByAirDate()':
../EpisodeNext/mainwindow.cpp:199: error: no matching function for call to 'qSort(QList<TvShow*>::iterator, QList<TvShow*>::iterator, <unresolved overloaded function type>)'
../../QtSDK/Simulator/Qt/gcc/include/QtCore/qalgorithms.h:184: note: candidates are: void qSort(RandomAccessIterator, RandomAccessIterator, LessThan) [with RandomAccessIterator = QList<TvShow*>::iterator, LessThan = bool (MainWindow::*)(TvShow*, TvShow*)]
make: *** [mainwindow.o] Error 1
Run Code Online (Sandbox Code Playgroud)

知道什么可能是错的吗?我正在使用最新版本的Qt SDK(Qt SDK 1.1 RC和Qt 4.7.3)

提前致谢!

小智 12

Robin,除了你需要在MainWindow.cpp文件中将"compareShowsByName"函数声明为全局之外,你做的一切正确.所以像这样的代码编译并正常工作:

bool compareShowsByName(TvShow* showA, TvShow* showB)
{
    return showA->getShowName() < showB->getShowName();
}

QList<TvShow*> MainWindow::orderShowsByName()
{
    QList<TvShow*> orderedShowList = appSettings.TvShows;
    qSort(orderedShowList.begin(), orderedShowList.end(), compareShowsByName);
    return orderedShowList;
}
Run Code Online (Sandbox Code Playgroud)

注意:除非您想在MainWindow之外的某个地方(在应用程序的任何其他部分中)使用它,否则您不一定需要在MainWindow.h中声明"compareShowsByName".但是,如果您仍然希望将"compareShowsByName"声明为MainWindow类的成员函数,则只需 正确传递指向成员函数指针即可.

希望有所帮助.