2014-01-09 115 views
0

我有一個Foo類,它有一個主函數和執行函數。我想用execute函數啓動未知數量的線程,但是當我嘗試編譯代碼時,我總是得到error C2064: term does not evaluate to a function taking 1 arguments多線程 - 類中的異步線程

foo.h中

#ifndef BOT_H 
#define BOT_H 

#pragma once 
#include <WinSock2.h> 
#include <WS2tcpip.h> 
#include <string> 
class foo 
{ 
public: 
    foo(char *_server, char *_port); 
    ~foo(void); 
private: 
    char *server; 
    char *port; 

    void execute(char *cmd); 
    void main(); 
}; 

#endif 

foo.c的

#include <thread> 
#include "bot.h" 
#include "definitions.h" 

using namespace std; 
foo::foo(char *_server, char *_port){ 
     ... 
} 

bot::~bot(void) { 
     ... 
} 
void bot::execute(char *command){ 
    ... 
} 
    void bot::main(){ 
     thread(&bot::execute, (char*)commanda.c_str()).detach(); 
    } 

我應該如何創建類的成員函數的線程?

感謝您的任何答案

回答

5

你需要一個bot對象調用的成員函數:

thread(&bot::execute, this, (char*)commanda.c_str()) 
         ^^^^ 

雖然你真的應該要麼改變採取任何std::stringconst char*功能。如果這個函數試圖修改字符串,或者線程仍在使用它,則會導致commanda被破壞。

lambda可能更具可讀性;並且還通過捕獲字符串的副本來修復終身慘敗:

thread([=]{execute((char*)commanda.c_str();})