微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

函数指针

#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

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐