一、引言
當我們在 C++ 中直接像 C 那樣使用類的成員函數指針時,通常會報錯,提示你不能使用非靜態的函數指針:
reference to non-static member function must be called
兩個解決方法:
把非靜態的成員方法改成靜態的成員方法
正確的使用類成員函數指針(在下面介紹)
關於函數指針的定義和使用你還不清楚的話,可以先看這篇博客了解一下:
https://blog.csdn.net/afei__/article/details/80549202
二、語法
1. 非靜態的成員方法函數指針語法(同C語言差不多):
void (*ptrStaticFun)() = &ClassName::staticFun;
2. 成員方法函數指針語法:
void (ClassName::*ptrNonStaticFun)() = &ClassName::nonStaticFun;
注意調用類中非靜態成員函數的時候,使用的是 類名::函數名,而不是 實例名::函數名。
三、實例:
#include <stdio.h>
#include <iostream>
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;
}
一個類中定義函數指針綁定另一個類的成員函數