我需要在類中調用另一個方法來調用另一個新線程中的同一個類,但是遇到了一些麻煩。我得到了編譯錯誤:「'這個'不可用於靜態成員函數」。我舉了一個例子,因爲我不能在這裏發佈原始代碼。如何使一個方法在新線程的同一個類中調用另一個方法?
基本上,我發生了什麼事是我的班級的一個對象(在下面的例子中被稱爲aClass
),然後我調用一個方法,如do_stuff()
。 do_stuff()
方法使用pthread_create
在新線程中調用print_number()
方法。問題是,當我去編譯時,我得到一個錯誤,說我不能使用this
,因爲我的print_number()
方法是靜態的。如果我沒有將print_number()
方法設爲靜態,則pthread_create
會抱怨它不是兼容的類型。
我明白爲什麼我不能在print_number()
方法本身內部使用this
,因爲它是靜態的,可以在沒有對象的情況下被調用。但是,在我的print_number()
方法中,我沒有使用this
。我正在使用指向我創建的對象的指針。在do_stuff()
我使用this
將我創建的對象的引用傳遞給print_number
,但我在print_number
本身中不使用this
。所以我不明白這個問題是什麼。謝謝您的幫助!
class aClass
{
private:
number;
public:
void do_stuff(void);
static void* print_number(void* arg)
}
// this method is called first
void aClass::do_stuff()
{
number = 4;
pthread_t thread1;
pthread_create(&thread1, NULL, print_number, this);
.....
}
//this method is called from the do_stuff() method in a new thread
void* aClass::print_number(void* arg)
{
aClass* objPTR = (aClass*)arg;
printf("number = %d", objPTR->number);
}
//don't get caught up here.. the point is that an object is created and
// the "do_stuff()" method is called
int main()
{
//all the usual stuff here
aClass someObject;
someObject.do_stuff();
}
查找「pthread_create類方法」。例如,這個問題可以解決這個問題:(http://stackoverflow.com/questions/7809987/c-how-to-define-a-class-method-as-a-start-routine-to -thread-with-pthread-lib) – MichaelGoren