以前用函数指针用的少。但是今天遇到了一个需要改写的项目,里面出现了函数指针的使用。假如一个类中有一个成员是函数指针,则声明函数指针的方式如下:
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中采用的近似算法。计算效果: