前些日子,在stack overflow上看到一个关于类中函数指针的问题:
There is a class
class A { public: A() {}; private: void func1( int) {}; void func2( int) {}; };
I want to add a function pointer which will be set in constructor and points to func1 or func2.
So I can call this pointer (as class member) from every class procedure and set this pointer in constructor.
How can I do it?
One Answer:
class A { public: A(bool b) : func_ptr_(b ? &A::func1 : &A::func2) {}; void func(int i) {(this->*func_ptr_)(i);} private: typedef void (A::*func_ptr_t_)(); func_ptr_t_ func_ptr_; void func1(int) {}; void func2(int) {}; };
That said, polymorphism might be a better way to do whatever you want to do with this.
关于类中的函数指针,当时一直不能理解为什么成员函数的指针一定要有显示地(A::func1)标识出来,成员函数与C里常用的函数有什么区别呢?
前些天,看了C++ Effective中关于成员函数里有个隐藏的this指针作为参数,我还是没把C的函数与类中成员函数的区别联系到函数指针用法上来。
直到今天,看了stanford的公开课programming paradigms的第五集,当jerry cain谈到lsearch这个function中的void* (*cmp)(void*, void*)必须得是真正的function,关于他如何说明这个真正,我贴上他的讲义: