typedefint(*fp)(int,int);intadd(inta,intb){returna+b;}intimp(inta,intb,fpf){return(*f)(a,b);}intmain(){printf("result is %i",imp(1,1,add));return0;}
3.两种定义形式
C: 返回类型 (*函数指针名称)(参数类型,参数类型,参数类型,…);
C++: 返回类型 (类名称::*函数成员名称)(参数类型,参数类型,参数类型,…);
4.函数指针作为返回值
12345678910111213141516171819202122
int(*foo(charop))(inta,intb){if(op=='+'){returnadd;}else{return0;}}void(*signal)(intsigno,void(*func)(int))(int);//unix 系统函数//函数名称signal//接受两个参数- int 和 一个函数指针//返回函数指针类型为: void(*)(int)//照着读signal 调用两次以后返回voidintmain(){int(*returnpf)(inta,intb);// (*returnpf) 这个括号不能少returnpf=foo('+');printf("result is %i\n",(*returnpf)(1,3));//orprintf("result is %i\n",foo('+')(1,1));}
structA;typedefstruct{void(*A)(structA*);void(*update)(structA*);int(*access)(structA*);}A_functable;typedefstructA{inta;A_functable*vmt;}A;voidA_A(A*this);voidA_update(A*this);intA_access(A*this);A_functableA_vmt={A_A,A_update,A_access};voidA_A(A*this){this->vmt=&A_vmt;this->a=10;}voidA_update(A*this){this->a++;}intA_access(A*this){this->vmt->update(this);returnthis->a;}/*class B: public A {public: void update() {a--;}};*/structB;typedefstruct{void(*B)(structB*);void(*update)(structB*);int(*access)(structA*);}B_functable;typedefstructB{Ainherited;}B;voidB_B(B*this);voidB_update(B*this);B_functableB_vmt={B_B,B_update,A_access};voidB_B(B*this){A_A(this);this->inherited.vmt=&B_vmt;}voidB_update(B*this){this->inherited.a--;}intB_access(B*this){this->inherited.vmt->update(this);returnthis->inherited.a;}intmain(){Ax;By;A_A(&x);B_B(&y);printf("%d\n",x.vmt->access(&x));printf("%d\n",y.inherited.vmt->access(&y));}