c++ - Function Pointer (Within Class) -
i'm trying use function pointer (fnptr) reference class method (fnempty) within class method, (in case constructor).
the setup program main.cpp is
#include <iostream> #include "test.hpp" int main(int argc, char* argv[]){ test test; return 0; }
and test.hpp reads
#ifndef _test_h #define _test_h #include <iostream> class test { private: public: void (*ptrempty)(void); void fnempty(){ std::cout << "got here" << std::endl;}; test(){ ptrempty = fnempty; }; ~test(){}; }; #endif
most of material on net details being able reference class method from outside class (see microsoft page , newty.de), not from inside class (as have done).
using above files gives error
in file included main.cpp:6: ./test.hpp:11:21: error: reference non-static member function must called;
so 1) why error result?
if change fnptr declaration on line 10 static reads
static void fnempty(){ std::cout << "got here" << std::endl;};
this seems solve problem. begs question 2) why accept 'static' if error says 'non-static' allowed?
if remove static , instead change line 11 (by adding &) reads
test(){ ptrempty = &fnempty; };
i whole new error reads
./test.hpp:11:21: error: must explicitly qualify name of member function when taking address
unfortunately replacing with
test(){ test::ptrempty = test::&fnempty; };
or variations not including test:: prefix done in links given above not solve problem.
i under impression far function pointers go, when referencing function (say fn),
ptr = fn;
is equivalent
ptr = &fn;
3) why getting 2 different sets of errors when include , exclude '&'
so ultimate question have is::
4) correct way point class method (from within different method of same class)? need include 'classname::' qualifier when within same class?
thanks, jeff
fnempty
non-static member function, means takes implicit first argument, pointer test
instance it's being invoked on (the this
pointer). type of pointer member function is
void (test::*ptrempty)();
next, form pointer member function, need use syntax &classname::memfnname
so, within constructor
ptrempty = &test::fnempty;
now example should compile. can invoke function ptrempty
points using
test t; (t.*(t.ptrempty))();
when change fnempty
static
no longer receives implicit this
pointer argument, it's other pointer function, , code compiles.
Comments
Post a Comment