综合大家的建议,您的最终解决方案将如下所示:
#include <iostream>
using std::cout;
usind std::endl;
class foo; // tell the compiler there's a foo out there.
class bar
{
public:
// If you want to store a pointer to each type of function you'll
// need two different pointers here:
void (*freeFunctionPointer)();
void (foo::*memberFunctionPointer)();
};
class foo
{
public:
bar myBar;
void hello(){ cout << "hello" << endl; }
};
void byebye()
{
cout << "bye" << endl;
}
int main()
{
foo testFoo;
testFoo.myBar.freeFunctionPointer = &byebye;
testFoo.myBar.memberFunctionPointer = &foo::hello;
((testFoo).*(testFoo.myBar.memberFunctionPointer))(); // calls foo::hello()
testFoo.myBar.freeFunctionPointer(); // calls byebye()
return 0;
}
C++ FAQ Lite有一些关于如何简化语法的指导。
采纳 Chris 的想法并付诸实践,你可以得到这样的结果:
#include <iostream>
using std::cout; using std::endl;
class foo;
typedef void (*FreeFn)();
typedef void (foo::*MemberFn)();
class bar
{
public:
bar() : freeFn(NULL), memberFn(NULL) {}
void operator()(foo* other)
{
if (freeFn != NULL) { freeFn(); }
else if (memberFn != NULL) { ((other)->*(memberFn))(); }
else { cout << "No function attached!" << endl; }
}
void setFreeFn(FreeFn value) { freeFn = value; memberFn = NULL; }
void setMemberFn(MemberFn value) { memberFn = value; freeFn = NULL; }
private:
FreeFn freeFn;
MemberFn memberFn;
};
class foo
{
public:
bar myBar;
void hello() { cout << "foo::hello()" << endl; }
void operator()() { myBar(this); }
};
void bye() { cout << "bye()" << endl; }
int main()
{
foo testFoo;
testFoo();
testFoo.myBar.setMemberFn(&foo::hello);
testFoo();
testFoo.myBar.setFreeFn(&bye);
testFoo();
return 0;
}