1

我正在尝试在父类中声明一个静态类并对其进行初始化,但我似乎遇到了各种错误。

/* 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;andMainWindow::hWin = new MainWindow((MainWindow*) param));和许多其他方法,但似乎都没有。这样做的正确方法是什么?有没有人会推荐关于这个主题的任何资源,我已经纠结class了几天的问题并且非常沮丧。

4

2 回答 2

4

静态成员始终由声明定义组成,您的 cpp 文件中缺少定义。将以下行放在任何函数之外:

MainWindow* MainWindow::hWin;

您可以在此处此处阅读更多信息。

于 2012-02-23T12:42:03.447 回答
0

在您的示例中使用静态变量将不允许您拥有多个实例,因此最好尽可能避免使用它。在您的示例中,不需要使用一个,您可以轻松地使用局部变量。

只需static MainWindow *hWin;从您的类定义中删除,并修改 MainWindow::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;
    }
于 2012-02-23T12:58:33.863 回答