我知道這已被問了很多次,因此很難挖掘cruft並找到一個簡單的例子。C++類的成員回調簡單的例子
我這有,它的簡單和它的作品爲MyClass
...
#include <iostream>
using std::cout;
using std::endl;
class MyClass
{
public:
MyClass();
static void Callback(MyClass* instance, int x);
private:
int private_x;
};
class EventHandler
{
public:
void addHandler(MyClass* owner)
{
cout << "Handler added..." << endl;
//Let's pretend an event just occured
owner->Callback(owner,1);
}
};
EventHandler* handler;
MyClass::MyClass()
{
private_x = 5;
handler->addHandler(this);
}
void MyClass::Callback(MyClass* instance, int x)
{
cout << x + instance->private_x << endl;
}
int main(int argc, char** argv)
{
handler = new EventHandler();
MyClass* myClass = new MyClass();
}
class YourClass
{
public:
YourClass();
static void Callback(YourClass* instance, int x);
};
那怎麼可以這樣改寫EventHandler::addHandler()
既要對付MyClass
和YourClass
工作。我很抱歉,但這只是我的大腦的工作方式,我需要看到一個簡單的例子,說明在我能理解爲什麼/如何工作之前,哪些方法可行。如果您現在有一個最喜歡的方式來完成這項工作,請將該代碼標記並重新發布。
[編輯]
有人回答,但答案被刪除之前,我可以給複選標記。 我的答案是模板函數。更改addHandler到這...
class EventHandler
{
public:
template<typename T>
void addHandler(T* owner)
{
cout << "Handler added..." << endl;
//Let's pretend an event just occured
owner->Callback(owner,1);
}
};
誰發佈了模板化函數示例?您有複選標記,但您在測試時刪除了您的答案。它完全符合我的需要。一個簡單的函數模板在我讀的所有其他信息的燉菜中迷失了。您的答案添加爲編輯問題。 – BentFX
我認爲這是JaredC。你可能需要追捕他= P – WhozCraig