In C language, you can use the function address to directly call a function:
Void print () {printf ("function print");} typdef void (* fun) (); fun f = print; f ();
In C ++, non-static class member functions must be called through instances. In C ++, class member functions must be called:
Class test {public: void print () {printf ("function print ");}};
We can also call the following by defining the function pointer:
Typedef void (test: * fun) (); fun f = & test: print; test t; (t. * f )();
What if we want to get the function address? An error is reported when the transfer is strong.
Unsigned int a = reinterpret_cast <unsigned int> (f); // compilation error char buf [32] = {0}; sprintf (buf, "% u", f ); int a = atoi (buf );
In fact, we know that the first parameter of a class member function is the this pointer, but this pointer is not pushed to the stack through common function parameters, but is put into ecx.
In C ++, how does one obtain the function pointer of a class member function?
Global functions, or static function pointers of classes, are well obtained, but how can we obtain and call common member function pointers?
Use an actual code to describe.
Class A {public: static void staticmember () {cout <"static" <endl;} // static member void nonstatic () {cout <"nonstatic" <endl ;}// nonstatic member virtual void virtualmember () {cout <"virtual" <endl ;}; // virtual member }; int main () {A a; // The static member function obtains the actual address of the function in the memory. Because the static member is global, :: qualifier void (* ptrstatic) () = & A: staticmember; // what the nonstatic member function obtains is the actual address of the function in the Memory void (A: * ptrnonstatic )() = & A: nonstatic; // The virtual function obtains the offset value in the virtual function table, which ensures the same polymorphism effect void (A: * ptrvirtual) during pointer calls) () = & A: virtualmember; // usage of the function pointer ptrstatic (); (. * ptrnonstatic) (); (. * ptrvirtual )();}