函數指針的聲明方法

以前用函數指針用的少。但是今天遇到了一個需要改寫的項目,裏面出現了函數指針的使用。假如一個類中有一個成員是函數指針,則聲明函數指針的方式如下:

T (* funcPtr)(T1, T2,....);

T是函數的返回類型,T1,T2...是輸入參數。

下面的代碼給出一個使用示例。

頭文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

private:
    float       (* m_fPtr)(float);//函數指針聲明
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

cpp文件(部分代碼來自https://blog.csdn.net/xtlisk/article/details/51249371):

#include "mainwindow.h"
#include "ui_mainwindow.h"

float fQuake3(float x)
{
    float xhalf = 0.5 * x;
    int i = *(int*)&x; // get bits for floating value
    i = 0x5f3759df - (i >> 1); // gives initial guess
    x = *(float*)&i; // convert bits back to float
    x = x * (1.5 - xhalf * x * x); // Newton step

    //版權聲明:本文爲CSDN博主「xtlisk」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
    //原文鏈接:https://blog.csdn.net/xtlisk/article/details/51249371

    return 1/x;
}

float fSqrt(float x)
{
    return sqrt(x);
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->RBtnSQRT->setChecked(true);
}

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

void MainWindow::on_pushButton_clicked()
{
    if(ui->RBtnQuake3->isChecked())
    {
        m_fPtr = fQuake3;
    }
    else
    {
        m_fPtr = fSqrt;
    }

    float fInput = ui->doubleSpinBox->value();
    float fOutput = m_fPtr(fInput);
    ui->doubleSpinBox_2->setValue((double)fOutput);
}

注意m_fPtr的使用。

這個程序允許用戶採用兩種方法計算平方根。一種是c++ math庫中自帶的sqrt函數,另一種採用卡馬克在quake3中採用的近似算法。計算效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章