2014-03-30 36 views
3

我原型我的功能我mainwindow.h類文件的非靜態成員函數(在QT)(標題):無效使用

class MainWindow : public QMainWindow 
{ 
    Q_OBJECT 

    public: 
    void receiveP(); 

然後在我的main.cpp類文件,我告訴該函數做什麼:

void MainWindow::receiveP() 
{ 
    dostuff 
} 

然後在我的main.cpp類文件的主要功能我試着在一個線程中使用它:

std::thread t1(MainWindow::receiveP); 
t1.detach(); 

這給了我錯誤「無效使用非靜態成員函數'void MainWindow :: receiveP()'。

回答

5

您試圖將成員函數指針傳遞給thread類的構造函數,該類需要普通(非成員)函數指針。

傳遞一個靜態方法函數指針(或指向一個自由函數)來代替,並明確給出你對象的實例:

// Header: 
static void receivePWrapper(MainWindow* window); 

// Implementation: 
void MainWindow::receivePWrapper(MainWindow* window) 
{ 
    window->receiveP(); 
} 

// Usage: 
MainWindow* window = this; // Or whatever the target window object is 
std::thread t1(&MainWindow::receivePWrapper, window); 
t1.detach(); 

確保線程終止你的窗口對象之前被破壞。