2011-04-10 69 views
3

好吧,我想排序我自己的TvShow類的列表,以按用戶決定的順序顯示TvShows列表。這是我在閱讀qSort()的文檔後得出的結論。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; 
} 

當然這失敗,以下錯誤:

../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 

任何想法可能是錯誤的?我正在使用最新版本的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; 
} 

注意:你不一定需要在MainWindow.h申報「compareShowsByName」除非你想的地方使用它主窗口外(在任何其他部分你的應用程序)。但是,如果您仍然想要將「compareShowsByName」聲明爲MainWindow類的成員函數,只需正確傳遞pointer to a member-function即可。

希望有所幫助。

+0

很好的答案!非常感謝! – 2011-04-10 20:36:44

+0

您到「指向成員函數的指針」的鏈接在此處被打破 – Chris 2017-08-08 19:08:28