函数指针

#include <iostream>
int add(int a, int b) 
{
    return a + b;
}
int sub(int a, int b)
{
    return a - b;
}
void func(int e, int d, int(*f)(int a, int b)) { // 这里才是我想说的,
                                                 // 传入了一个int型,双参数,返回值为int的函数
    std::cout << f(e, d) << std::endl;
}
int main()
{
    func(2, 3, add);
    func(2, 3, sub);
    system("pause");
    return 0;
}

通过函数指针调用函数:

#include<iostream>
using namespace std;
int foo(int x)
{
    return x;
}

int main()
{
    int(*funcPtr)(int) = foo;
    cout<<(*funcPtr)(5)<<endl; // 通过funcPtr调用foo(5)
    funcPtr(5);// 也可以这么使用,在一些古老的编译器上可能不行
    system("pause");
    return 0;
}

把一个函数赋值给函数指针:

#include<iostream>
using namespace std;
int foo()
{
    return 5;
}

int goo()
{
    return 6;
}

int main()
{
    int(*funcPtr)() = foo; // funcPtr 现在指向了函数foo
    cout << "funcPtr的地址是:" << funcPtr << endl ;
    cout << "指针函数调用的结果是:" << funcPtr() << endl << endl;
    funcPtr = goo; // funcPtr 现在又指向了函数goo
    cout << "funcPtr的地址是:" << funcPtr << endl;   //但是千万不要写成funcPtr = goo();这是把goo的返回值赋值给了funcPtr
    cout << "指针函数调用的结果是:" << funcPtr() << endl << endl;
    system("pause");
    return 0;
}

链接:https ://zhuanlan.zhihu.com/p/37306637

原文地址:https://www.cnblogs.com/yibeimingyue/p/10071734.html