C++ 类成员函数的函数指针

1、引言
当咱们在 C++ 中直接像 C 那样使用类的成员函数指针时,一般会报错,提示你不能使用非静态的函数指针:ios

reference to non-static member function must be called函数

两个解决方法:this

把非静态的成员方法改为静态的成员方法
正确的使用类成员函数指针(在下面介绍)
 spa

关于函数指针的定义和使用你还不清楚的话,能够先看这篇博客了解一下:.net

https://blog.csdn.net/afei__/article/details/80549202指针

 

2、语法
1. 非静态的成员方法函数指针语法(同C语言差很少):
void (*ptrStaticFun)() = &ClassName::staticFun;
2. 成员方法函数指针语法:
void (ClassName::*ptrNonStaticFun)() = &ClassName::nonStaticFun;
注意调用类中非静态成员函数的时候,使用的是 类名::函数名,而不是 实例名::函数名。blog

 

3、实例:
#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;
}
 博客

相关文章
相关标签/搜索