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

下面两个链接讲的不错
https://blog.csdn.net/afei__/article/details/81985937
https://linux.cn/article-13498-1.html

下面的例子参考了链接1,并有所补充。


#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 FuncD(int a, int b) {
        return a + b;
    }
  
    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::FunA); //不能调用静态方法
    obj->pFun2(&MyClass::FunB);
    obj->pFun2(&MyClass::FunC);
    
    int (MyClass::*methodPtrFunc)(int, int);
    methodPtrFunc = &MyClass::FuncD;
    cout << (obj->*methodPtrFunc)(3, 5) << endl;

    
    delete obj;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值