C++ 函数指针

2018-03-24 17:31 更新

学习C++ - C++函数指针

声明一个函数的指针

指向函数的指针必须指定指针指向什么类型的函数。

声明应该识别函数的返回类型和函数的参数列表。

声明应提供与函数原型相同的功能相同的信息。

假设我们有以下函数。

double my_func(int);  // prototype

下面是一个适当指针类型的声明:

double (*pf)(int);

pf指向一个使用一个int参数并返回类型double的函数。

我们必须把括号围绕* pf提供适当的运算符优先级。

括号的优先级高于*运算符。

*pf(int)表示pf()是一个返回指针的函数。

(*pf)(int)表示pf是指向函数的指针。

在您正确声明pf后,您可以为其赋值匹配函数的地址:

double my_func(int); 
double (*pf)(int); 
pf = my_func;           // pf now points to the my_func() function 

my_func()必须匹配签名和返回类型的pf。


使用指针调用函数

(*pf)起到与函数名称相同的作用。

我们可以使用(*pf),就像它是一个函数名一样:

double (int); 
double (*pf)(int); 
pf = my_func;            // pf now points to the my_func() function 
double x = my_func(4);   // call my_func() using the function name 
double y = (*pf)(5);     // call my_func() using the pointer pf 

例子

以下代码演示了在程序中使用函数指针。


#include <iostream>
using namespace std;

double my_func(int);
void estimate(int lines, double (*pf)(int));

int main(){
    int code = 40;

    estimate(code, my_func);
    return 0;
}

double my_func(int lns)
{
    return 0.05 * lns;
}

void estimate(int lines, double (*pf)(int))
{
    cout << lines << " lines will take ";
    cout << (*pf)(lines) << " hour(s)\n";
}

上面的代码生成以下结果。



以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号