我在下面提供了示例代码。我想使用功能指针从公共函数c::PubFn
调用c::LocFn2
。当我评论行时,pp[1].fp();
代码正常工作。请帮助我。
#include <iostream>
using namespace std;
class c
{
public:
void PubFn();
private:
struct p
{
int a;
int b;
int (c::*fp)();
};
static const p pp[];
int LocFn1();
int LocFn2();
};
void c::PubFn() {
cout << "Val = "<< pp[1].a << "n"; //It prints 3 correctly.
pp[1].fp(); //Here I wanna call c::LocFn2 using the function pointer.
}
int c::LocFn1() {
cout << "This is loc fn1n";
return 0;
}
int c::LocFn2() {
cout << "This is loc fn2n";
return 0;
}
const c::p c::pp[] = { {1, 2, &c::LocFn1}, {3, 4, &c::LocFn2} };
int main()
{
c obj;
obj.PubFn();
}
使用指针到会员操作员->*
。
(this->*(pp[1].fp))();
额外的括号是必要的