- 指向一般函数的指针
//指向函数的指针
typedef int (*GenFunc)(int, int);
//使用时,指针前带*和不带*都一样,如:
int Test(GenFunc fun, int a, int b)
{
return (*fun)(a, b);
}
int Test2(GenFunc fun, int a, int b)
{
return fun(a, b);
}
- 指向类的成员函数的指针
类的静态成员函数与一般函数指针相同,类的非静态成员函数与一般函数指针不同,而且,指向不同类的非静态成员函数的指针也不兼容。指向类的非静态成员函数的指针,在声明时就需要添加类名。
class Foo;
//指向类的非静态成员函数的指针
typedef int (Foo::*ClassFunc)(int, int);
class Foo {
public:
int Add(int a, int b)
{
return a + b;
}
static int Sum(int a, int b)
{ return a + b; }
/*类里面使用类的非静态成员函数指针*/
int Test(ClassFunc fun, int a, int b)
{
return (this->*fun)(a, b);//fun前面必须带*,否则编译错误
}
};
/*类外使用类的非静态成员函数指针*/
int Test(Foo* foo, ClassFunc fun, int a, int b)
{
return (foo->*fun)(a, b);//fun前面必须带*,否则编译错误
}