您的位置:58编程 > c++函数指针 C++ 函数指针

c++函数指针 C++ 函数指针

2023-04-06 18:33 C++教程

c++函数指针 C++ 函数指针

c++函数指针 C++ 函数指针

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

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



阅读全文
以上是58编程为你收集整理的c++函数指针 C++ 函数指针全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
© 2024 58编程 58biancheng.com 版权所有 联系我们
桂ICP备12005667号-32 Powered by CMS