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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM