当它是一个类数据成员时,如何调用成员函数的指针? [英] How to invoke pointer to member function when it's a class data member?
本文介绍了当它是一个类数据成员时,如何调用成员函数的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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 ?
}
在上面的测试代码中, pf
是 B
的数据成员。调用它的语法规则是什么?这应该是直接,但我没有得到一个适当的匹配。例如如果我尝试 obj。* pf(0,0);
然后我得到:
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) (...)’
推荐答案
像这样:
(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);
因为函数调用的优先级高于成员运算符的指针,所以你不能: / p>
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)
因为这相当于:
obj.*(obj.pf(0, 1)) // grammar expects obj.pf to be a callable returning a
// pointer to member
这篇关于当它是一个类数据成员时,如何调用成员函数的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文