2014-07-04 26 views
0

所以我做了一個小的多文件代碼,所以它會更容易表現出我的問題我在與SDL線程問題無法創建線程SDL多檔節目

頭文件

#ifndef MAINC_H_INCLUDED 
#define MAINC_H_INCLUDED 
#include <iostream> 
#include <CONIO.H> 
#include <SDL.h> 
#include <SDL_thread.h> 
using namespace std; 
class mainc 
{ 
    private: 
     SDL_Thread* thread; 
     int threadR; 
     int testN=10; 
    public: 
     int threadF(void *ptr); 
     int OnExecute(); 
     bool start(); 
}; 
#endif 

一個文件

#include "mainc.h" 
bool mainc::start() { 
if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { 
    return false; 
} 
getch(); 
if(SDL_CreateThread(threadF, "TestThread", (void *)NULL)==NULL){ 
return false; 
} 
return true; 
} 

int mainc::threadF(void *ptr){ 
cout<<"This is a thread and here is a number: "<<testN<<endl; 
return testN; 
} 

第二個文件

#include "mainc.h" 

int mainc::OnExecute() { 
    if(!start()) 
    { 
     return -1; 
    } 
    SDL_WaitThread(thread,&threadR); 
    return 0; 
} 

int main(int argc, char* argv[]) { 
    mainc game; 

    return game.OnExecute(); 
} 

當我編譯這個我得到這個錯誤

cannot convert 'mainc::threadF' from type 'int (mainc::)(void*)' to type 'SDL_ThreadFunction {aka int (*)(void*)}' 

我周圍挖一點,我發現了一個解決方案,但它給了我,我需要做threadF靜態其他錯誤,但我不能訪問它給我的任何變量這個錯誤

invalid use of member 'mainc::testN' in static member function 

但是,如果我從函數刪除變量運行良好 現在我不知道該怎麼做,因爲在我的遊戲我需要共享哪些改變

+0

成員函數指針不是函數指針。 – Quentin

回答

0

testN既不是一個變量靜態也不是一個mainc類的公共屬性,並且做你想做的事情,它也需要做。 如果你想使用類「mainc」的成員從另一個線程體中,你需要一個指針傳遞給類「mainc」的目的是SDL_CreateThread:

// ... 
SDL_CreateThread(threadF, "TestThread", this) 
// ... 

然後

int mainc::threadF(void *ptr) 
{ 
    mainc* myMainc = (mainc*)ptr; 
    myMainc->testN; // now you can use it as you need 
} 

小心封裝,儘管(testN實際上是私有的)

+0

謝謝你的工作,但有什麼辦法來取代myMainc-> testN;只測試N;因爲我需要一些時間才能習慣它。 – MFanatik

+0

您可以調用線程體內的公共類方法,使其成爲線程體。 – Socket2104