【发布时间】:2010-04-30 16:00:29
【问题描述】:
这有几个重复,但没有人解释为什么我可以使用成员变量来存储指针(在 FOO 中)但是当我尝试使用局部变量时(在 BAR 的注释部分),它是非法的。有人能解释一下吗?
#include <iostream>
using namespace std;
class FOO
{
public:
int (FOO::*fptr)(int a, int b);
int add_stuff(int a, int b)
{
return a+b;
}
void call_adder(int a, int b)
{
fptr = &FOO::add_stuff;
cout<<(this->*fptr)(a,b)<<endl;
}
};
class BAR
{
public:
int add_stuff(int a, int b)
{
return a+b;
}
void call_adder(int a, int b)
{
//int (BAR::*fptr)(int a, int b);
//fptr = &BAR::add_stuff;
//cout<<(*fptr)(a,b)<<endl;
}
};
int main()
{
FOO test;
test.call_adder(10,20);
return 0;
}
【问题讨论】:
-
为了避免与真正的函数指针或“函数指针”类型的成员变量混淆,我避免调用指向成员函数的指针,“成员函数指针”。在许多方面,指向成员函数的指针与指向数据成员的指针的共同点比与函数指针的共同点要多。
标签: c++ class member-function-pointers