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

时间:2014-11-27 02:21:44

标签: c++ multithreading pointers member-function-pointers member-functions

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

#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在高级...

2 个答案:

答案 0 :(得分:0)

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

恰好有语法错误:0 this

答案 1 :(得分:0)

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

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

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

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

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