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

一、引言
当我们在 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;
}

一个类中定义函数指针绑定另一个类的成员函数

 
class A;
class B
{
public:
void(A::*p)();
};
 
class A
{
public:
void set()
{
B b;
b.p = &A::print;
(this->*(b.p))();
}
 
private:
void print()
{
std::cout << "a print" << std::endl;
}
};
 
int main()
{
A a;
a.set();
return 0;
}
原文地址:https://www.cnblogs.com/lidabo/p/15427864.html