最近遇到了函数指针的内容,有部分遗忘,经过复习巩固后,写下这篇博客,方便以后查看

函数指针基础:

1.获取函数的地址

2.声明一个函数指针

3.使用函数指针来调用函数

获取函数指针:

函数的地址就是函数名,要将函数作为参数进行传递,必须传递函数名。

声明函数指针

声明指针时,必须指定指针指向的数据类型,同样,声明指向函数的指针时,必须指定指针指向的函数类型,这意味着声明应当指定函数的返回类型以及函数的参数列表。

例如:

1
2
3
4
5
6
double cal(int);   // prototype
double (*pf)(int); // 指针pf指向的函数, 输入参数为int,返回值为double
pf = cal; // 指针赋值

void (Teacher:: *teacherSignal)(QString) = &Teacher::hungry; //定义函数指 teacherSignal指向函数hungry,并接受一个QString类型的参数
connect(zt, teacherSignal, st, studentSlot);

如果将指针作为函数的参数传递:

1
void estimate(int lines, double (*pf)(int));  // 函数指针作为参数传递 

使用指针调用函数

1
2
3
double y = cal(5);   // 通过函数调用
double y = (*pf)(5); // 通过指针调用 推荐的写法
double y = pf(5); // 这样也对, 但是不推荐这样写

函数指针的使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;

double cal_m1(int lines)
{
return 0.05 * lines;
}

double cal_m2(int lines)
{
return 0.5 * lines;
}

void estimate(int line_num, double (*pf)(int lines))
{
cout << "The " << line_num << " need time is: " << (*pf)(line_num) << endl;
}

int main(int argc, char *argv[])
{
int line_num = 10;
// 函数名就是指针,直接传入函数名
estimate(line_num, cal_m1);
estimate(line_num, cal_m2);
return 0;
}