How to invoke pointer to member function when it's a class data member?

拜拜、爱过 提交于 2019-12-17 16:18:24

问题


struct B
{
  void (B::*pf)(int, int);  // data member
  B () : pf(&B::foo) {}
  void foo (int i, int j) { cout<<"foo(int, int)\n"; } // target method
};

int main ()
{
  B obj;
  // how to call foo() using obj.pf ?
}

In above test code, pf is a data member of B. What's the grammar rule to invoke it ? It should be straight forward, but I am not getting a proper match. e.g. If I try obj.*pf(0,0); then I get:

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘pf (...)’, e.g. ‘(... ->* pf) (...)’

回答1:


Like this:

(obj.*obj.pf)(0, 1);

Member access (.) has a higher precedence than a pointer to member operator so this is equivalent to:

(obj.*(obj.pf))(0, 1);

Because function call also has higher precedence than a pointer to member operator, you can't do:

obj.*obj.pf(0, 1) /* or */ obj.*(obj.pf)(0, 1)

As that would be equivalent to:

obj.*(obj.pf(0, 1)) // grammar expects obj.pf to be a callable returning a
                    // pointer to member



回答2:


pf is a method pointer, and you want to invoke the method it points to, so you have to use

(obj.*obj.pf)(1, 2);

It says the object obj you invoke the method pointed by pf

See result here :

http://ideone.com/p3a5G




回答3:


The syntax is quite unnatural but a consequence of C++ precedence rules...

(obj.*obj.pf)(1, 2);


来源:https://stackoverflow.com/questions/6316751/how-to-invoke-pointer-to-member-function-when-its-a-class-data-member

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