您应该阅读如何在 C++ 中实现回调?并特别注意对观察者模式的引用。如果您有两个这样紧密耦合的类,那么您可能需要重新考虑您的设计,因为测试它们很快就会变成一场噩梦。
也就是说,这里是如何完成你开始的实施......
#include <iostream>
class First;
// Typedefs make this much more readable: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.5
typedef void (First::*SecondTriggeredCallback)(void);
// And macros make the call much more readable: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.6
#define CALL_MEMBER_FN(object, ptrToMember) ((object).*(ptrToMember))
class Second
{
public:
// You'll also need an *instance* of the First class
Second(SecondTriggeredCallback SecondTriggered, First& first)
{
CALL_MEMBER_FN(first, SecondTriggered)();
}
};
class First
{
private:
Second *second;
public:
First()
{
std::cout << "first class was created" << std::endl;
second = new Second(&First::SecondTriggered, *this);
}
~First()
{
delete second;
}
void SecondTriggered()
{
std::cout << "second class was created and responded" << std::endl;
}
};
int main()
{
First first;
}
看它跑!
这是一个使用模板消除耦合的版本:
#include <iostream>
// Macros make the call much more readable: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.6
#define CALL_MEMBER_FN(object, ptrToMember) ((object).*(ptrToMember))
template <class T>
struct Second
{
// Typedefs make this much more readable: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.5
typedef void (T::*SecondTriggeredCallback)(void);
// You'll also need an *instance* of the "T" class
Second(SecondTriggeredCallback SecondTriggered, T& t)
{
CALL_MEMBER_FN(t, SecondTriggered)();
}
};
class First
{
public:
First()
:second(NULL)
{
std::cout << "first class was created" << std::endl;
second = new Second<First>(&First::SecondTriggered, *this);
}
~First()
{
delete second;
}
void SecondTriggered()
{
std::cout << "second class was created and responded" << std::endl;
}
private:
First(const First&);
First& operator =(const First&);
Second<First>* second;
};
int main()
{
First first;
}