2011-11-25 24 views
2

「錯誤:無效使用非靜態數據成員的線程:: tfun「的」如何在類中使用函數指針?

Class thread { 

    typedef void* (th_fun) (void*); 

    th_fun *tfun; 

    void create(th_fun *fun=tfun) { 

    pthread_create(&t, NULL, fun, NULL); 

} 

} 

如何有一個類中的函數指針?

請注意: - 靜態減速會使代碼編譯。但我的要求是保持每個對象的功能。

+1

可能重複http://stackoverflow.com/questions/8079453/c-class-member-function-callback/8079610#8079610 – Yousf

+0

不完全是......我需要存儲/修改。使用其他時間。 – rakesh

+0

爲什麼不使用'boost :: thread'? –

回答

3

您使用pthreads很好,而且您在這裏沒有指向成員函數。

的問題是,你要使用非靜態成員變量作爲一個功能的默認參數,並you can't do that

struct T { 
    int x; 

    void f(int y = x) {} 
}; 
// Line 2: error: invalid use of non-static data member 'T::x' 
// compilation terminated due to -Wfatal-errors. 

默認參數必須是東西是—基本—一個全球,或至少一個不需要資格的名稱。

幸運的是,這是一個簡單的修復!

Class thread { 

    typedef void* (th_fun) (void*); 
    th_fun* tfun; 

    void create(th_fun* fun = NULL) {  // perfectly valid default parameter 
    if (fun == NULL) { 
     fun = tfun;      // works now because there's an object 
    }         // context whilst we're inside `create` 

    pthread_create(&t, NULL, fun, NULL); 
    } 
}; 
0

你不能使用非靜態成員函數t來做到這一點。

你可以做的是通過參數void *class thread的指針傳遞給t。或者如果您仍然有其他參數t,則可以將它們全部(包括指向class thread)包裝在結構中,並傳遞結構實例的指針。

正如其他人所說,只有extern "C"功能將符合pthread_create的需要。

+0

您無法將靜態成員函數傳遞給'pthread_create';如果你的編譯器符合C++標準,它將不會編譯。你傳遞的函數必須是'extern「C'',並且成員函數,甚至靜態的,都不能。 –

+0

哦,那會是一個問題。我對'pthread_create'不太熟悉。 – fefe