一、函数指针的使用
float MyFunc(int x,char* p)
{
cout<<p<<endl;
return x;
}
typedef float (*my_func_ptr)(int,char*);
my_func_ptr Func;
Func = &MyFunc; //Func = MyFunc;也可以
(*Func)(1, "hello");
二、成员函数指针(Member Function Pointer)
class SomeClass
{
public:
float Some_Member(int x,char* p)
{
cout<<p<<endl;
return x;
}
};
typedef float (SomeClass::*my_member_ptr)(int,char*);
my_member_ptr Func;
Func = &SomeClass::Some_Member;
SomeClass someclass;
(someclass.*Func)(2,"hello");
SomeClass* pclass = new SomeClass;
Func = &SomeClass::Some_Member;
(pclass->*Func)(3,"hello");
三、带单继承的成员函数指针
class SomeClass {
public:
virtual void some_member_func(int x, char *p) {
printf("In SomeClass"); };
};
class DerivedClass : public SomeClass {
public:
// If you uncomment the next line, the code at line (*) will fail!
// virtual void some_member_func(int x, char *p) { printf("In DerivedClass"); };
};
int main() {
// Declare a member function pointer for SomeClass
typedef void (SomeClass::*SomeClassMFP)(int, char *);
SomeClassMFP my_memfunc_ptr;
my_memfunc_ptr = &DerivedClass::some_member_func; // ---- line (*)
}
四、带多继承的成员函数指针
五、委托(delegate)
使用委托可以很容易地实现一个Subject/Observer设计模式的改进版。Observer(观察者)模式显然在GUI中有很多的应用,但我发现它对应用程序核心的设计也有很大的作用。委托也可用来实现策略(Strategy)和状态(State)模式。