2014-01-07 73 views
0


我需要在類中調用另一個方法來調用另一個新線程中的同一個類,但是遇到了一些麻煩。我得到了編譯錯誤:「'這個'不可用於靜態成員函數」。我舉了一個例子,因爲我不能在這裏發佈原始代碼。如何使一個方法在新線程的同一個類中調用另一個方法?

基本上,我發生了什麼事是我的班級的一個對象(在下面的例子中被稱爲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(); 
} 
+0

查找「pthread_create類方法」。例如,這個問題可以解決這個問題:(http://stackoverflow.com/questions/7809987/c-how-to-define-a-class-method-as-a-start-routine-to -thread-with-pthread-lib) – MichaelGoren

回答

0

U需要使print_number聲明在類中靜態。 只是下面的代碼

class aClass 
{ 
    private: 
    int number; 

    public: 
    void do_stuff(void); 
    static void* print_number(void* arg); 

}; 

這僅僅只是類部分替換線

class aClass 
{ 
    private: 
    number; 

    public: 
    void do_stuff(void); 
    void* print_number(void* arg) 

}; 

。 編譯它希望它能解決你的問題。

+0

實際上,在真實的代碼中,我確實有靜態寫在類的一部分。我忘了寫在我的例子中。對於那個很抱歉!修改上面的例子。 – Michael

相關問題