这个概念主要用在C++中去实现"委托"的特性.
但现在C++11 中有了 更好用的function/bind 功能.
但对于类的成员函数指针的概念我们还是应该掌握的.
类函数指针 就是要确定由哪个 类的实例 去调用 类函数指针所指的函数
第一部分:函数指针?
float add(float a, float b) { return a + b; }
float sub(float a, float b) { return a - b; }
typedef float(*pf)(float, float);
float foo(float a, float b, pf op){
float y = op(a, b);
return y;
}
pf bar(const char* mode = "add") {
if (mode == "add")
return add;
else
return sub;
}
第二部分:类方法指针:?
class A {
public:
int add(int x, int y) { return x + y; }
int sub(int x, int y) { return x + y; }
int mul(int x, int y)const { return x * y; }
int div(int x, int y)const { return x / y; }
};
typedef int (A::*pfunc)(int, int) const;
//pfunc div1 = &A::div;
int Div(int x, int y,const A& self, pfunc op){
return (self.*op)(x,y);
}
void test() {
//测试1:
int (A::*fp)(int, int) = &A::add;
A a;
cout << "1.1.add= " << (a.*fp)(10, 20) << endl;
//测试2:
typedef int (A::*f)(int, int);
f add = &A::add;
cout << "2.1.add=" << (a.*add)(10, 20) << endl;
cout << "2.2.add=" << (a.*&A::add)(10, 20) << endl;
cout << "2.3.add= " << (a.A::add)(10, 20) << endl;
//测试3:
int (A::*fp1)(int, int)const = &A::mul;
cout << "3.1.add= " << (a.*fp1)(10, 20) << endl;
//测试4:
typedef int (A::*f1)(int, int) const;
f1 mul = &A::mul;
cout << "4.1.add=" << (a.*mul)(10, 20) << endl;
cout << "4.2.add=" << (a.*&A::mul)(10, 20) << endl;
cout << "4.3.add= " << (a.A::mul)(10, 20) << endl;
//测试5:
cout << "5.1.Div=" << Div(100, 2, a, &A::div) << endl;
}
int main(){
test();
}
|