在C++中,函数指针可以作为函数的参数传递,这样可以灵活地在运行时决定调用哪个函数。下面是使用函数指针作为函数参数的示例:
- #include <iostream>
-
- // 定义一个接受两个int参数并返回int的函数指针类型
- typedef int (*Operation)(int, int);
-
- // 加法函数
- int add(int a, int b) {
- return a + b;
- }
-
- // 减法函数
- int subtract(int a, int b) {
- return a - b;
- }
-
- // 执行操作函数,接收两个操作数和一个函数指针作为参数
- int performOperation(int a, int b, Operation op) {
- return op(a, b);
- }
-
- int main() {
- // 使用加法函数指针调用 performOperation 函数
- int result = performOperation(5, 3, add);
- std::cout << "Addition result: " << result << std::endl;
-
- // 使用减法函数指针调用 performOperation 函数
- result = performOperation(5, 3, subtract);
- std::cout << "Subtraction result: " << result << std::endl;
-
- return 0;
- }
在上面的示例中,我们首先定义了一个函数指针类型 Operation,它接受两个 int 参数并返回 int。然后,我们实现了两个具体的操作函数 add 和 subtract。performOperation 函数接收两个操作数和一个函数指针作为参数,根据函数指针的值来决定调用哪个具体的操作函数。