2013-03-11 73 views
0

我寫了一個非常簡單的線程代碼。由於我對此很新,所以我不知道所提到的錯誤。錯誤:類型爲「void(opca_hello ::)()」的參數不匹配「void *(*)(void *)」

class opca_hello 
{ 
public: 
void hello(); 
} 

void opca_hello::hello() 

{ 
printf ("hello \n"); 
} 


int main(int argc, char **argv) 
{ 
opca_hello opca; 
pthread_t thread1, thread2; 
pthread_create(&thread1, NULL, opca.hello, NULL); 
pthread_join(thread1, NULL); 
return 0; 
} 

錯誤:類型的自變量 「空隙(opca_hello ::)()」 不匹配 「空隙*(*)(無效*)」

+6

成員函數指針不是一回事函數指針。你的成員函數有一個參數。 – chris 2013-03-11 04:55:29

+0

感謝您的回覆@chris您能否澄清一下。我的意思是我需要更改代碼的位置。 – sajal 2013-03-11 05:02:50

+0

你需要給它一個指向沒有參數的函數的指針。 – chris 2013-03-11 05:04:41

回答

3

C++調用成員函數需要通過一個指針以及其餘的論點。

所以使用線程這樣寫代碼:

static void *start(void *a) 
{ 
    opca_hello *h = reinterpret_cast<opca_hello *>(a); 
    h->hello(); 
    return 0; 
} 

pthread_create(&thread1, NULL, start, &opca); 

PS:

如果您需要將參數傳遞給方法做這樣的事情(例如):

結構threadDetails {opa_hello * obj; int p; };

static void *start(void *a) 
{ 
    struct threadDetails *td = reinterpret_cast<struct threadDetails *>(a); 
    td->obj->hello(td->p); 
    delete td; 
    return 0; 
} 

然後:

struct threadDetails *td = new struct threadDetails; 
td->obj = &opca; 
td->p = 500; 
pthread_create(&thread1, NULL, start, td); 
+0

出現錯誤:: Main.cpp:4:錯誤:âvoid*â不是指向對象的類型。 如果稍後我更改我的代碼以在hello中調用函數,則不能使用靜態。對? – sajal 2013-03-11 05:29:08

+0

@sajal - 我的錯 - 修正了上面的代碼。 – 2013-03-11 05:36:54

+0

@NicolBolas - 你的權利 - 大腦還沒有裝備。 – 2013-03-11 05:42:59

相關問題