求教,C++类中创建线程函数的有关问题
求教,C++类中创建线程函数的问题
麻烦各位高手了,还望赐教。
有一个类,两个函数。一个函数是线程函数:
编译后提示:
然后,按照网上说的,在线程函数前加static,出现如下提示:
接下来怎么办……不想把 i 也设置成static。
不知道这个问题应该发到线程板块还是类板块,于是就这么发了,如果管理员觉得不妥,可以移到基础类板块
------解决方案--------------------
线程必须是类的静态函数,否则,肯定不行,因为附加的,类非静态函数必须传递this指针
------解决方案--------------------
#include <windows.h>
#include <stdio.h>
class Class
{
public:
static int i;
static DWORD WINAPI ThreadProc( LPVOID lpParameter );
int StartThread();
};
DWORD WINAPI Class::ThreadProc( LPVOID lpParameter )
{
int j = (int)lpParameter;
// i = 2;
printf("%d\n", i);
return 0;
}
int Class::StartThread()
{
CreateThread(NULL, 0, ThreadProc, (LPVOID)2, 0, 0);
Sleep(1000);
return 0;
}
int Class::i;
int main()
{
Class c1;
c1.StartThread();
return 0;
}
麻烦各位高手了,还望赐教。
有一个类,两个函数。一个函数是线程函数:
#include <windows.h>
#include <stdio.h>
class Class
{
public:
int i;
DWORD WINAPI ThreadProc( LPVOID lpParameter );
int StartThread();
};
DWORD WINAPI Class::ThreadProc( LPVOID lpParameter )
{
int j = (int)lpParameter;
printf("%d + %d = %d\n", i, j, i + j);
return 0;
}
int Class::StartThread()
{
CreateThread(NULL, 0, ThreadProc, (LPVOID)123, 0, 0);
}
int main()
{
Class c1;
c1.StartThread();
return 0;
}
编译后提示:
--------------------Configuration: Cpp1 - Win32 Debug--------------------
Compiling...
Cpp1.cpp
D:\System\桌面\Cpp1.cpp(27) : error C2664: 'CreateThread' : cannot convert parameter 3 from 'unsigned long (void *)' to 'unsigned long (__stdcall *)(void *)'
None of the functions with this name in scope match the target type
执行 cl.exe 时出错.
Cpp1.obj - 1 error(s), 0 warning(s)
然后,按照网上说的,在线程函数前加static,出现如下提示:
--------------------Configuration: Cpp1 - Win32 Debug--------------------
Compiling...
Cpp1.cpp
D:\System\桌面\Cpp1.cpp(20) : error C2597: illegal reference to data member 'Class::i' in a static member function
D:\System\桌面\Cpp1.cpp(20) : error C2597: illegal reference to data member 'Class::i' in a static member function
执行 cl.exe 时出错.
Cpp1.obj - 1 error(s), 0 warning(s)
接下来怎么办……不想把 i 也设置成static。
不知道这个问题应该发到线程板块还是类板块,于是就这么发了,如果管理员觉得不妥,可以移到基础类板块
c++
类
线程
win32
------解决方案--------------------
线程必须是类的静态函数,否则,肯定不行,因为附加的,类非静态函数必须传递this指针
------解决方案--------------------
#include <windows.h>
#include <stdio.h>
class Class
{
public:
static int i;
static DWORD WINAPI ThreadProc( LPVOID lpParameter );
int StartThread();
};
DWORD WINAPI Class::ThreadProc( LPVOID lpParameter )
{
int j = (int)lpParameter;
// i = 2;
printf("%d\n", i);
return 0;
}
int Class::StartThread()
{
CreateThread(NULL, 0, ThreadProc, (LPVOID)2, 0, 0);
Sleep(1000);
return 0;
}
int Class::i;
int main()
{
Class c1;
c1.StartThread();
return 0;
}