一、引言
当我们在 c 中直接像 c 那样使用类的成员函数指针时,通常会报错,提示你不能使用非静态的函数指针:
reference to non-static member function must be called
两个解决方法:
把非静态的成员方法改成静态的成员方法
正确的使用类成员函数指针(在下面介绍)
二、语法
1. 非静态的成员方法函数指针语法(同c语言差不多):
void (*ptrstaticfun)() = &classname::staticfun;
- 成员方法函数指针语法:
void (classname::*ptrnonstaticfun)() = &classname::nonstaticfun;
注意调用类中非静态成员函数的时候,使用的是 类名::函数名,而不是 实例名::函数名。
三、实例:
#include
#include
using namespace std;
class myclass {
public:
static int funa(int a, int b) {
cout << "call funa" << endl;
return a b;
}
void funb() {
cout << "call funb" << endl;
}
void func() {
cout << "call func" << endl;
}
int pfun1(int (*p)(int, int), int a, int b) {
return (*p)(a, b);
}
void pfun2(void (myclass::*nonstatic)()) {
(this->*nonstatic)();
}
};
int main() {
myclass* obj = new myclass;
// 静态函数指针的使用
int (*pfuna)(int, int) = &myclass::funa;
cout << pfuna(1, 2) << endl;
// 成员函数指针的使用
void (myclass::*pfunb)() = &myclass::funb;
(obj->*pfunb)();
// 通过 pfun1 只能调用静态方法
obj->pfun1(&myclass::funa, 1, 2);
// 通过 pfun2 就是调用成员方法
obj->pfun2(&myclass::funb);
obj->pfun2(&myclass::func);
delete obj;
return 0;
}