问题
I am trying to create a thread in an object, however I get an error saying '&' : illegal operation on bound member function expression.
Reading up I saw I have to make the member function static, but when I do that I get an error saying left of '.dac_ping' must have class/struct/union
this is what I am trying:
class Dac
{
private:
network_com com;
HANDLE ping_thread;
DWORD dping_thread;
static DWORD WINAPI ping_loop(void* param)
{
while ( com.dac_ping() == 0)
Sleep(900);
return 1; //since this is an infinite loop, if the loop breaks, it has failed
}
public:
Dac()
{
}
~Dac()
{
}
void find_dac()
{
com.find_dac();
com.print_dac_info();
}
void connect_and_keep_alive()
{
if (com.dac_connect() == 0)
ping_thread = CreateThread (NULL , 0, ping_loop, NULL, 0, &dping_thread);
}
};
回答1:
static
functions aren't bound to a particular instance; there is no this
pointer, and you have no "member variables." You can pass the this
pointer as an argument to your function, and then cast it into a Dac*
and access member variables from it.
So you could do
ping_thread = CreateThread (NULL , 0, ping_loop, (LPVOID)this, 0, &dping_thread);
And change your ping_loop
to this:
static DWORD WINAPI ping_loop(void* param)
{
Dac* dac = (Dac*)param;
while ( dac->com.dac_ping() == 0)
Sleep(900);
return 1; //since this is an infinite loop, if the loop breaks, it has failed
}
来源:https://stackoverflow.com/questions/8025049/problems-using-createthread-on-a-member-function