Calling pointer-to-member function C++

只谈情不闲聊 提交于 2019-11-28 00:58:54

问题


I have a pointer to a member function defined within a class, e.g.:

class Example {
   void (Example::*foo)();

   void foo2();
};

In my main code, I then set foo as:

Example *a;
a->foo = &Example::foo2;

However, when I try to call foo:

a->foo();

I get the following compile time error: "error: expression preceding parentheses of apparent call must have (pointer-to-) function type". I'm assuming I'm getting the syntax wrong somewhere, can someone point it out to me?


回答1:


to call it you would do: (a->*(a->foo))()

(a->*X)(...) - dereferences a member function pointer - the parens around a->*X are important for precedence.

X = a->foo - in your example.

See ideone here for working example



来源:https://stackoverflow.com/questions/23686456/calling-pointer-to-member-function-c

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