2014-02-18 86 views
0
//This is AsynchronousFunction class header file 

typedef int (*functionCall)(int, int); 

DWORD __stdcall functionExecuter(LPVOID pContext); // global function 

class AsynchronousFunction 
{ 

    int param1, param2; 
    functionCall fCall; 
    HANDLE m_handle; 

public: 
    AsynchronousFunction(functionCall, int, int); 
    ~AsynchronousFunction(); 
    int result(); 

protected: 
private: 
    int returnVal; 

}; 


It's implementation as follows 

AsynchronousFunction::AsynchronousFunction(functionCall fCall, int param1, int  param2):m_handle(CreateEvent(NULL , false , false , NULL)) 
{ 
    bool b = QueueUserWorkItem(functionExecuter, this, WT_EXECUTEDEFAULT); 

    WaitForSingleObject(m_handle, INFINITE); 
    SetEvent(m_handle); 
} 

AsynchronousFunction::~AsynchronousFunction() 
{ 
    CloseHandle(m_handle); 
} 

int AsynchronousFunction::result() 
{ 

    return 0;// not implemented yet 

} 

DWORD __stdcall functionExecuter(LPVOID pContext) 
{ 

    return 0; 

} 

此处pContext接收“this”指针。我的尝试是从这里访问param1和param2
并执行工作 我该怎么做?如何将“this”指针传递给全局函数

回答

1

要么你可以让functionExecuterAsynchronousFunction 或 一个朋友在AsynchronousFunction这确实需要的东西添加公共职能和functionExecuter调用它,类似如下所示。

DWORD __stdcall functionExecuter(LPVOID pContext) 
{ 
    return (reinterpret_cast<AsyncrhonousFunction*>(pContext))->realFunctionExecuter(); 
} 
+0

我个人更喜欢避免朋友,除非绝对必要,甚至于是再次猜测,看看是否有其他方式。所以我更喜欢后一种方法。它看起来也很干净。 – jia103

+0

@ jia103我同意你的意见。第二选项看起来更清洁我也亲自避免朋友功能 –

+0

谢谢。我知道了。由于pContext是一个void指针,因此需要将其转换为AsynchronousFunction类型。 – Zarco

0

@sajas对不起,我根本就没有提及斯科特迈尔斯的书或香草萨特的书以外的明确提及;这只是我一路上拾起的东西之一。一般来说,如果不需要隐私私人数据,那么您不想破坏封装,这正是其所做的。在这种情况下,如果您决定明天更改AsynchronousFunction的执行方式,并且functionExecuter是其朋友,则更可能因为它可能依赖私人成员而打破functionExecuter;另一方面,如果它从不是朋友开始,那么只能使用AsynchronousFunction的公共接口来编码functionExecuter