如何创建指向函数C++的指针的线程

How to create a thread of a pointer to a function C++

本文关键字:C++ 函数 指针 线程 何创建 创建      更新时间:2023-10-16

我知道为了在对象上创建方法的线程,我可以这样做:

#include <thread> 
using namespace std;
class Character
{
public:
    void myFunction(int a){ /* */ }
    void startThreadMyFunction(int a){
      thread Mf1(&Character::myFunction, this, a);
    }
};

我也知道,为了在我的类中有一个指向函数的指针,我可以这样做:

#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.
    }
};

我的问题是,当我尝试同时使用这两件事时,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.
    }
};

有谁知道如何解决它?TY 在高级...

问题是指向成员函数的指针不是指向自由函数的指针。 std::thread可以同时使用两者,但您需要保持一致。

在第一个示例中,您有一个指向成员函数的指针。好的。

在第二个示例中,您有一个指向自由函数的指针。也行。

在第三个示例中,FMoveForward 是指向自由函数的指针。 &Character::FMoveForward是指向指针的指针。这是行不通的。

如果要存储&Character::myFunction,则需要一个void (Character::*FMoveForward)(int);成员。这是指向成员函数的指针

thread Mf1(&Character::FMoveForward ,0 this, delay);// The VS 13 Complain because the sintaxe os this line.

碰巧有一个语法错误:0 this