指向函数的指针必须指定指针指向什么类型的函数。
声明应该识别函数的返回类型和函数的参数列表。
声明应提供与函数原型相同的功能相同的信息。
假设我们有以下函数。
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++ 嵌套 switch 语句 C++ 判断您可以把一个 switch 作为一个外部 switch 的语句序列的一部分,即可以在一个 switch 语句内使用...
在面试C++方面的工作时,经常会遇到各种面试题,这对应聘人员的知识掌握能力要求较高。本文将为大家带来的就是19道必须掌握的C++...
C 库函数 - getc() C 标准库 - stdio.h描述C 库函数 int getc(FILE *stream) 从指定的流 stream 获取下一个字符(一个无符号字符...
C 库函数 - memmove() C 标准库 - string.h描述C 库函数 void *memmove(void *str1, const void *str2, size_t n) 从 str2 复制 ...
打开第一个页面的“MainAbilitySlice.java”文件,重写onStart()方法添加按钮的响应逻辑,实现点击按钮跳转到下一页,示例代码如...
ByteArrayInputStreamjava.lang.Object |---java.io.InputStream |---|---java.io.ByteArrayInputStreampublic class ByteArrayI...