2017-10-12 33 views
0

我在寫一個非常簡單的C++程序。錯誤:無法調用成員函數'void Fortest :: run()'without object |

#include<iostream> 
#include<thread> 

class Fortest{ 
private: 
    int x; 
public: 
    Fortest(int a) 
    { 
     x=a; 
    } 
    void run(void) 
    { 
     cout<<"test sucesses!"<<endl; 
    } 
}; 

int main() 
{ 
    Fortest hai(1); 
    std::thread t; 

    t=std::thread(std::ref(hai),&Fortest::run()); 
    t.join(); 

    cout<<"program ends"<<endl; 
    return 0; 
} 

而且我不斷收到錯誤「無法調用沒有對象的成員函數」。任何人都可以幫我解決這個問題嗎?

+1

可能有[Sta rt線程與成員函數](https://stackoverflow.com/questions/10673585/start-thread-with-member-function) – Borgleader

回答

2

你有問題:

第一個是你呼叫線程函數,指針傳遞到其返回值。您應該傳遞一個指向函數的指針。

第二個問題是您以錯誤的順序傳遞std::thread constructor參數。指向函數的指針是的第一個參數,要調用它的對象是第二個(這是該函數的第一個參數)。

I.e.它應該像

t = std::thread(&Fortest::run, &hai); 
0

要調用了錯誤的方式

嘗試:

Fortest hai(1); 
std::thread t; 

t=std::thread(&Fortest::run, std::ref(hai)); 
t.join(); 

或這樣做的t=std::thread(&Fortest::run, &hai); 檢查std::thread

Live demo

參數
相關問題