四、函数指针的使用

1.函数指针和指针函数区别

函数指针:函数指针指向函数的地址,是个指针变量,本质是个指针变量

int func();

int (*nfunc)()=&func;

指针函数:返回值为指针的函数,本质还是个函数

2.QT中函数指针的应用

1>定义

类内函数指针的定义需要指定作用域,不是本作用域下不可用,例如

int (MainWindow::*nfunc)(int a,int b);

非类内函数指针不需要指定作用域

int (nfunc)(int a,int b);

2>调用

如果在类内调用,需要指定this,类外需要有指定的对象,因为需要实际内存空间

int func(int a,int b);
nfunc=&MainWindow::func;
(this->*nfunc)(1,2);

3.案例

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    int (func)(int a,int b);

private:
    Ui::MainWindow *ui;
    int (MainWindow::*nfunc)(int a,int b);
};
#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);
    nfunc=&MainWindow::func;
    (this->*nfunc)(1,2);
}

MainWindow::~MainWindow()
{
    delete ui;
}

int MainWindow::func(int a, int b)
{
    qDebug()<<a<<b;
    return 0;
}

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值