关于C++函数指针的思考

函数指针是什么?

在程序运行中,函数代码是程序的算法指令部分,他们和数组一样也占用存储空间,并都有相应的地址。可以使用指针变量指向数组的首地址,也可以使用指针变量指向函数代码的首地址,指向函数代码首地址的指针变量称为函数指针。例如:

int fun(int x);
int(*f)(int x);//参数列表必须和对应函数一样
f = fun;

在这段代码中将函数指针f指向了fun函数的入口地址,然后我们就可以通过指针 f 来调用函数fun:

#include <iostream>
using namespace::std;

int fun(int x){
    cout << "I am function fun!" << endl;
    return x+1;
}
int main()
{
    int(*f)(int x);
    f = fun;
    int num = (*f)(5); //也可以用f(5)
    cout << "My num now is " << num << endl;
    return 0;
}

这里写图片描述
但是,光是这样的功能,总让人产生疑问,为什么我不直接调用函数呢?还要声明一个函数指针?函数指针好用的地方在于能在 “运行时根据数据的具体状态来选择相应的处理方式”。这主要在它能作为函数的参数 这一功能中体现。

#include <iostream>
#include <string>

using namespace::std; 

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int fun1(int x){
    cout << "I am function fun1!" << endl;
    return x;
}
int fun2(int x){
    cout << "I am function fun2!" << endl;
    return x;
}
int fun3(int x){
    cout << "I am function fun3!" << endl;
    return x;
}
typedef int (*pf)(int x);
int use_fun_ptr(pf p,int x)
{
    int result = 0;
    result = (*p)(x);
    cout << "我输入的数字是: " << result << endl;
}


int main()
{   
    use_fun_ptr(fun1, 5);
    use_fun_ptr(fun2, 6);
    use_fun_ptr(fun3, 7);
    return 0;
}

这里写图片描述
我们可以看到,根据我们传入函数的不同,use_fun_ptr()函数也就调用了不同的函数。
参考博客:
https://blog.csdn.net/goodmentc/article/details/44257739
http://blog.51cto.com/hipercomer/792300

猜你喜欢

转载自blog.csdn.net/weixin_41713281/article/details/79818721