本文介绍了C ++函数指针(类成员)到非静态成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Foo {
public:
Foo() { do_something = &Foo::func_x; }
int (Foo::*do_something)(int); // function pointer to class member function
void setFunc(bool e) { do_something = e ? &Foo::func_x : &Foo::func_y; }
private:
int func_x(int m) { return m *= 5; }
int func_y(int n) { return n *= 6; }
};
int
main()
{
Foo f;
f.setFunc(false);
return (f.*do_something)(5); // <- Not ok. Compile error.
}
如何让这个工作?
推荐答案
您想要的行是
return (f.*f.do_something)(5);
(编译 - 我试过了)
(That compiles -- I've tried it)
* f.do_something
指的是指针本身---f告诉我们从 >。但是我们仍然需要给一个对象,当我们调用该函数时,它将是这个指针。这就是为什么我们需要 f。
前缀。
"*f.do_something
" refers to the pointer itself --- "f" tells us where to get the do_something value from. But we still need to give an object that will be the this pointer when we call the function. That's why we need the "f.
" prefix.
这篇关于C ++函数指针(类成员)到非静态成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!