C++中使用函数指针 【瓦特芯笔记】

时间:2023-03-09 21:10:42
C++中使用函数指针 【瓦特芯笔记】

     在C++类中使用函数指针。

类型定义:
     typedef 返回类型(类名::*新类型)(参数表)

//类定义

class CA

{

public:

char lcFun(int a) { return; }

};

     CA ca;
     typedef char (CA::*PTRFUN)(int);
     PTRFUN pFun;
    void main()
    {
       pFun = CA::lcFun;
       ca.(*pFun)(2);
    }
       

在这里,指针的定义与使用都加上了“类限制”或“对象”,用来指明指针指向的函数是那个类的这里的类对象也可以是使用new得到的。比如:
     CA *pca = new CA;
     pca->(*pFun)(2);
     delete pca;
     而且这个类对象指针可以是类内部成员变量,你甚至可以使用this指针。比如:类CA有成员变量PTRFUN m_pfun;

     void CA::lcFun2()
     {
         (this->*m_pFun)(2);
     }

 

一句话,使用类成员函数指针必须有“->*”或“.*”的调用。

在Qt下的demo:

 

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H #include <QMainWindow> namespace Ui {
class MainWindow;
} //接收返回类型
typedef enum{
MB_EX_NONE = 0x00,
MB_EX_ILLEGAL_FUNCTION = 0x01,
MB_EX_ILLEGAL_DATA_ADDRESS = 0x02,
MB_EX_ILLEGAL_DATA_VALUE = 0x03,
MB_EX_SLAVE_DEVICE_FAILURE = 0x04,
MB_EX_ACKNOWLEDGE = 0x05,
MB_EX_SLAVE_BUSY = 0x06,
MB_EX_MEMORY_PARITY_ERROR = 0x08,
MB_EX_GATEWAY_PATH_FAILED = 0x0A,
MB_EX_GATEWAY_TGT_FAILED = 0x0B
} eMBException; class MainWindow : public QMainWindow
{
Q_OBJECT public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow(); typedef eMBException (MainWindow::*pxMBFunctionHandler )(); typedef struct
{
quint8 ucFunctionCode;
pxMBFunctionHandler pxHandler;
} xMBFunctionHandler; xMBFunctionHandler test[2]; eMBException fun1();
eMBException fun2(); private:
Ui::MainWindow *ui;
quint8 value;
}; #endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug> MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this); test[0].pxHandler = &MainWindow::fun1;
test[1].pxHandler = &MainWindow::fun2; (this->*test[0].pxHandler)();
(this->*test[1].pxHandler)();
} MainWindow::~MainWindow()
{
delete ui;
} eMBException MainWindow::fun1(){
value = 1;
qDebug("call fun1();");
return MB_EX_NONE;
} eMBException MainWindow::fun2(){
value = 2;
qDebug("call fun2();");
return MB_EX_NONE;
}

 

 

main.cpp

#include "mainwindow.h"
#include <QApplication> int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show(); return a.exec();
}