初始化类中的静态数据成员(类) 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));
以及许多其他方法,但似乎都不起作用。执行此操作的正确方法是什么?有没有人会推荐关于这个主题的任何资源,我几天来一直在解决类问题,并且非常沮丧。
I am trying to declare a static class within a parent class and initialize it, but I seem to be getting all sorts of errors.
/* 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;
}
I have tried using MainWindow::hWin = (MainWindow*) param;
and MainWindow::hWin = new MainWindow((MainWindow*) param));
and many others, but none seem to work. What is the proper way to do this? Are there any resources anybody would recommend on this subject, I have been tangling with class
problems for a few days now and am very frustrated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
静态成员始终由声明和定义组成,您的cpp文件中缺少定义。将以下行放在任何函数之外:
您可以阅读更多 此处 或 此处。
Static members always consist of a declaration and a definition, you lack the definition in your cpp file. Put the following line outside of any functions:
You can read more here or here.
使用像示例中这样的静态变量将不允许您拥有多个实例,因此最好尽可能避免使用它。在您的示例中,无需使用局部变量,您可以轻松地使用局部变量。
只需从类定义中删除
static MainWindow *hWin;
,并修改 MainWindow::threadproc() 以使用局部变量:但是,如果您确实想要/必须使用静态变量(例如原因在您的示例中并不明显),那么我建议将其设置在 MainWindow 的 ctor 中 - 就在那里。无需显式地将其传递给线程。
Using a static variable like in your example will not allow you to have more than one instance, so it's best to avoid it if possible. And in your example there is no need to use one, you can easily use a local variable instead.
Just remove the
static MainWindow *hWin;
from your class definition, and modify MainWindow::threadproc() to use a local variable:However, if you really want to/have to use a static variable (for reasons that are not apparent in your example), then I'd suggest to set it in MainWindow's ctor - and just there. No need to explicitly pass it to the thread.