c++ member function pointer problem

∥☆過路亽.° 提交于 2019-11-28 12:11:24

Two errors corrected here:

int main()
{
   golu m, *n;
   void (golu::*t)() =&golu::man; 

   n=&m;
   (n->*t)();
}
  1. you want a pointer to function
  2. the priority of the operators is not the one you expected, I had to add parenthesis. n->*t(); is interpreted as (n->*(t())) while you want (n->*t)();

A member function pointer has the following form:

R (C::*Name)(Args...)

Where R is the return type, C is the class type and Args... are any possible parameters to the function (or none).

With that knowledge, your pointer should look like this:

void (golu::*t)() = &golu::man;

Note the missing () after the member function. That would try to call the member function pointer you just got and thats not possible without an object.
Now, that gets much more readable with a simple typedef:

typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;

Finally, you don't need a pointer to an object to use member functions, but you need parenthesis:

golu m;
typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;
(m.*t)();

The parenthesis are important because the () operator (function call) has a higher priority (also called precedence) than the .* (and ->*) operator.

'void golu:: *t =&golu::man();' should be changed to 'void (golu:: *t)() =&golu::man;' you are trying to use pointer to function not pointer to result of a static function!

(1) Function pointer is not declared properly.

(2) You should declare like this:

void (golu::*t) () = &golu::man;

(3) Member function pointer should be used with object of the class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!