函数数组指针示例

函数数组指针是一个指向函数指针数组的指针。它用于存储一组函数指针,使您可以通过函数指针数组的索引来调用不同的函数。函数数组指针通常用于实现函数表或分发不同的操作或处理不同的事件。

以下是一个简单的示例,说明如何声明和使用函数数组指针:

#include

// 定义几个示例函数
int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

int multiply(int a, int b) {
    return a * b;
}

int main() {
    // 声明函数指针数组,存储上述函数的指针
    int (*operation[3])(int, int) = {add, subtract, multiply};

    // 使用函数数组指针来调用不同的函数
    int result1 = operation[0](5, 3); // 调用add函数
    int result2 = operation[1](8, 2); // 调用subtract函数
    int result3 = operation[2](4, 6); // 调用multiply函数

    printf("Result 1: %d\n", result1); // 输出 8
    printf("Result 2: %d\n", result2); // 输出 6
    printf("Result 3: %d\n", result3); // 输出 24

    return 0;
}
在上面的示例中,我们定义了三个函数 addsubtractmultiply,然后声明了一个函数指针数组 operation,其中存储了这三个函数的指针。然后,我们使用函数数组指针来调用不同的函数,根据索引选择执行哪个函数。这使得我们可以通过一个统一的接口调用不同的函数,根据需要执行不同的操作。

你可能感兴趣的:(c++)