2012-02-23 115 views
1

我想在父類中聲明一個靜態類並初始化它,但我似乎得到各種各樣的錯誤。初始化一個類中的靜態數據成員(類)C++

/* MainWindow.h */ 
    class MainWindow 
    { 
     private: 
     static DWORD WINAPI threadproc(void* param); 
     static MainWindow *hWin; 
    }; 
/* MainWindow.cpp */ 
#include "MainWindow.h" 
     void MainWindow::on_pushButton_clicked() 
     { 
      HANDLE hThread = CreateThread(NULL, NULL, threadproc, (void*) this, NULL, NULL); 
      WaitForSingleObject(hThread, INFINITE); 
      CloseHandle(hThread); 
     } 

     DWORD WINAPI MainWindow::threadproc(void* param) 
     { 
      hWin = (MainWindow*) param; 
      //Be able to access stuff like hWin->run(); 
      return 0; 
     } 

我一直在使用MainWindow::hWin = (MainWindow*) param;MainWindow::hWin = new MainWindow((MainWindow*) param));和其他許多人嘗試過,但沒有一個似乎工作。什麼是正確的方法來做到這一點?有沒有人會推薦這個主題的資源,我幾天來一直在與class的問題糾纏在一起,我非常沮喪。

+1

你會得到哪些錯誤信息? – Lol4t0 2012-02-23 12:41:37

+0

C++中沒有靜態類。 (你有什麼是一個靜態數據成員。) – sbi 2012-02-23 12:43:23

回答

4

靜態成員總是由一個聲明和一個定義,你沒有在你的CPP文件中的定義。把下面的行中的任何功能外:

MainWindow* MainWindow::hWin; 

你可以閱讀更多herehere

+0

我得到:'錯誤:C2655:'MainWindow :: hWin':定義或重新聲明在當前範圍內是非法的,'錯誤:C2086:'MainWindow * MainWindow :: hWin':重新定義'當我使用你的代碼。 – user99545 2012-02-23 12:44:27

+0

更新了答案:您需要將定義放在任何函數之外。 – soulmerge 2012-02-23 12:45:52

+0

我不明白爲什麼C++會如此挑剔以至於在功能之外要求它。我會閱讀你發佈的鏈接,謝謝。 – user99545 2012-02-23 12:47:43

0

使用類似於您的示例中的靜態變量將不允許您有多個實例,因此如果可能,最好避免它。在你的例子中,不需要使用一個,你可以輕鬆地使用一個局部變量。

只是刪除從你的類定義static MainWindow *hWin;,並修改主窗口:: ThreadProc的()來使用局部變量:

DWORD WINAPI MainWindow::threadproc(void* param) 
    { 
     MainWindow* const hWin = static_cast<MainWindow*>(param); 
     //hWin->whatever(); 
     return 0; 
    } 

但是,如果你真的想/必須使用一個靜態變量(在你的例子中不明顯的原因),那麼我建議將它設置在MainWindow的ctor中 - 並且就在那裏。不需要顯式地將它傳遞給線程。

MainWindow::MainWindow() 
    { 
     assert(hWin == 0); 
     hWin = this; 
    } 

    MainWindow::~MainWindow() 
    { 
     assert(hWin == this); 
     hWin = 0; 
    } 

    void MainWindow::on_pushButton_clicked() 
    { 
     HANDLE hThread = CreateThread(0, 0, threadproc, 0, 0, 0); 
     WaitForSingleObject(hThread, INFINITE); 
     CloseHandle(hThread); 
    } 

    DWORD WINAPI MainWindow::threadproc(void*) 
    { 
     // just use hWin, it already points to the one and only MainWindow instance 
     return 0; 
    }