codecamp

C++ 函数指针

学习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";
}

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



C++ 函数参数
C++ 函数默认参数
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }