【问题标题】:Initializing a static data member (class) within a class C++在 C++ 类中初始化静态数据成员(类)
【发布时间】:2012-02-23 12:37:26
【问题描述】:

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

/* 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 问题并且非常沮丧。

【问题讨论】:

  • 你得到什么错误信息?
  • C++ 中没有静态类。 (您拥有的是静态数据成员。)

标签: c++ class static initialization redefinition


【解决方案1】:

静态成员总是由一个声明和一个定义组成,你的cpp文件中没有定义。将以下行放在任何函数之外:

MainWindow* MainWindow::hWin;

您可以阅读更多herehere

【讨论】:

  • 当我使用你的代码时,我得到:error: C2655: 'MainWindow::hWin' : definition or redeclaration illegal in current scope,error: C2086: 'MainWindow *MainWindow::hWin' : redefinition
  • 更新了答案:您需要将定义放在任何函数之外。
  • 我不明白为什么 C++ 会如此挑剔以至于在函数之外要求它。我会阅读您发布的链接,谢谢。
  • “总是”不太准确 - 您不需要定义从未odr-used 的整数常量。但在这种情况下你肯定需要一个。
  • @user99545:在代码块内定义的任何内容都在该代码块内限定范围,并且与在类、命名空间或不同块中声明的具有相同名称的任何内容不同。
【解决方案2】:

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

只需从类定义中删除 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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多