c++中有两种函数指针
- 普通函数指针
- 成员函数指针
而对于成员函数指针,又分为两种
- 静态成员函数指针
- 非静态成员函数指针
定义普通函数指针与静态函数指针的语法类似
void (*pa)();
定义非静态成员函数指针
void (A::* pa)();
在调用非静态成员函数时,实际上会传入对象的指针,因此,非静态成员函数的调用必须与具体的对象绑定。
下面来看一下通过指针调用静态成员函数和非静态成员函数的区别
#include <iostream>
void (*pStaticFunc)();
class A {
public:
static void staticFunc() {
std::cout << "staticFunc" << std::endl;
}
void f() {
std::cout << "non-staticFunc" << std::endl;
}
};
void(A::* pf)();
int main() {
A a;
pStaticFunc = &A::staticFunc;
pf = &A::f;
pStaticFunc();
(a.*pf)();
return 0;
}
运行结果
更复杂一点,我们要在类里面声明一个指向成员函数的指针,然后通过该函数指针调用成员函数,该怎么做呢
直接上代码
#include <iostream>
void (*pStaticFunc)();
class A {
public:
static void staticFunc() {
std::cout << "staticFunc" << std::endl;
}
void f() {
std::cout << "non-staticFunc" << std::endl;
}
void (A::* ptr)();
};
void(A::* pf)();
int main() {
A a;
pStaticFunc = &A::staticFunc;
pf = &A::f;
a.ptr = &A::f;
pStaticFunc();
(a.*pf)();
(a.*a.ptr)();
return 0;
}
运行结果
是不是很绕?绕就对了