[英]How to create a thread of a pointer to a function C++
I know that in order to create a thread of a method on an Object I can do it in this way: 我知道,为了在对象上创建方法的线程,我可以通过以下方式做到这一点:
#include <thread>
using namespace std;
class Character
{
public:
void myFunction(int a){ /* */ }
void startThreadMyFunction(int a){
thread Mf1(&Character::myFunction, this, a);
}
};
Also I know that in order to have a pointer to a function in my class I can do it in this way: 我也知道,为了在类中有一个指向函数的指针,我可以这样来做:
#include <thread>
using namespace std;
class Character
{
private:
void (*FMoveForward)(int);// Pointer to a function.
public:
void setCommands(void(mf)(int delay)){//This function sets the pointer.
FMoveForward = mf;
}
void MoveForward(int delay){
FMoveForward(delay);// Here a call my function with my pointer to function.
}
};
My problem is that all the time when I try to use both of these things together the Visual Studio 13 compiler always complain about the sintaxe. 我的问题是,当我尝试同时使用所有这些东西时,Visual Studio 13编译器总是抱怨sintaxe。
#include <iostream>
using namespace std;
class Character
{
private:
void (*FMoveForward)(int);
public:
void setCommands(void(mf)(int delay)){
FMoveForward = mf;
}
void MoveForward(int delay){
thread Mf1(&Character::FMoveForward , this, delay);// The VS 13 Complain because the sintaxe os this line.
}
};
Does anyone knows how to solve it? 有人知道如何解决吗? TY in advanced... TY进阶...
This 这个
thread Mf1(&Character::FMoveForward ,0 this, delay);// The VS 13 Complain because the sintaxe os this line.
happens to have a syntax error: 0 this
碰巧有语法错误: 0 this
The problem is that pointers to member functions are not pointers to free functions. 问题在于,指向成员函数的指针不是指向自由函数的指针。 std::thread
can use both, but you need to be consistent. std::thread
可以同时使用,但是您需要保持一致。
In your first example, you have a pointer to a member function. 在第一个示例中,您有一个指向成员函数的指针。 OK. 好。
In your second example, you have a pointer to a free function. 在第二个示例中,您有一个指向自由函数的指针。 Also OK. 还行。
In your third example, FMoveForward
is a pointer to a free function. 在您的第三个示例中, FMoveForward
是指向自由函数的指针。 &Character::FMoveForward
is a pointer to a pointer. &Character::FMoveForward
是指向指针的指针。 That's not going to work. 那是行不通的。
If you want to store &Character::myFunction
, you would need a void (Character::*FMoveForward)(int);
如果要存储&Character::myFunction
,则需要一个void (Character::*FMoveForward)(int);
member. 会员。 That's a pointer to a member function 那是一个指向成员函数的指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.