c++ 函数指针使用案例

函数指针是指向某一类函数的指针变量

demo1:

#include <iostream>

using namespace std;


int mysum1(int a, int b){
    return a + b;
}

int mysum2(int a, int b){
    return 2 * (a + b);
}

void myfac(int a, int b, int (*pf2)(int a,int b)){
    int sum = (*pf2)(a, b);
    cout << "sum:" << sum << endl;
}


int main(int argc, char *argv[])
{
    // 函数名就是指针,直接传入函数名
    myfac(2, 3, mysum1);
    myfac(2, 3, mysum2);
    return 0;
}

输出结果:
D:\C++Test\cmake-build-debug\C__Test.exe
sum:5
sum:10

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/alspd_zhangpan/article/details/107365359
今日推荐