函数指针及几种用法

函数指针

函数指针是指向函数的指针,可以用于在程序运行时动态地调用函数。函数指针是 C++ 中非常有用的概念,特别是在编写高级程序时,如操作系统、编译器等。

简单例子

函数指针的声明方式类似于一个函数声明,只需在函数名前加上一个 * 号即可:
return_type (*function_name)(parameter_list);
其中,return_type 是函数的返回类型,function_name 是函数名,parameter_list 是函数的参数列表。
下面是一个简单的示例,演示如何声明和使用函数指针:
#include <iostream>

void printMessage(const char* message) {
    std::cout << message << std::endl;
}

int main() {
    void (*pPrintMessage)(const char*);
    pPrintMessage = &printMessage;

    (*pPrintMessage)("Hello, world!");

    return 0;
}
在这个示例中,我们声明了一个函数指针 pPrintMessage,它指向一个接受一个 const char* 参数并返回 void 的函数。然后,我们将指针设置为指向 printMessage 函数,并使用指针调用该函数。
当调用函数指针时,可以使用圆括号来调用它,也可以使用箭头运算符(->)来调用它。例如,上面的示例中,我们使用了 (*pPrintMessage)("Hello, world!") 的语法来调用函数,也可以使用 pPrintMessage("Hello, world!") 的语法来调用它。

动态调用函数

#include <iostream>
using namespace std;

void func1() {
    cout << "This is function 1" << endl;
}

void func2() {
    cout << "This is function 2" << endl;
}

void invokeFunction(void (*func)()) {
    func();
}

int main() {
    // 动态选择要调用的函数
    int choice;
    cout << "Enter 1 for func1, 2 for func2: ";
    cin >> choice;
    if (choice == 1) {
        invokeFunction(&func1);
    }
    else if (choice == 2) {
        invokeFunction(&func2);
    }

    return 0;
}

回调函数

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void printNumber(int num) {
    cout << num << endl;
}

void forEach(vector<int>& vec, void (*func)(int)) {
    for (int i = 0; i < vec.size(); i++) {
        func(vec[i]);
    }
}

int main() {
    // 使用回调函数打印向量中的所有数字
    vector<int> vec = { 1, 2, 3, 4, 5 };
    forEach(vec, &printNumber);

    return 0;
}

函数指针作为函数返回值

#include <iostream>
using namespace std;

// 定义加法函数
int add(int x, int y) {
    return x + y;
}

// 定义减法函数
int subtract(int x, int y) {
    return x - y;
}

// 定义乘法函数
int multiply(int x, int y) {
    return x * y;
}

// 声明函数指针类型
typedef int (*Operation)(int, int);

// 定义返回函数指针的函数
Operation getOperation(char op) {
    switch (op) {
        case '+':
            return &add;
        case '-':
            return &subtract;
        case '*':
            return &multiply;
        default:
            return NULL;
    }
}

int main() {
    // 获取加法函数指针
    Operation op = getOperation('+');

    // 使用函数指针执行操作
    int result = op(2, 3);

    // 输出结果
    cout << "Result: " << result << endl;

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值