赞
踩
函数是一组接受输入、执行某些特定计算并产生输出的语句。使用函数的想法是一起执行一些常见或重复完成的任务并创建一个函数,这样就不必为不同的输入一次又一次地编写相同的代码。
函数的一般形式如下:
return_type function_name([ arg1_type arg1_name, ... ])
{
// 执行操作
}
将函数作为参数传递是 C++ 中的一个有用概念。在将自定义比较器函数作为std::sort()中的参数传递 以根据需要对对象序列进行排序时,已经使用了这个概念。在本文中,我们将讨论设计接受另一个函数作为参数的函数的不同方法。
函数可以作为参数传递,有 3 种方法,即
作为指针传递
使用 std::function<>
使用 Lambda
例子:
C++
// C++ program to pass function as a // pointer to any function #include <iostream> using namespace std; // Function that add two numbers int add(int x, int y) { return x + y; } // Function that multiplies two // numbers int multiply(int x, int y) { return x * y; } // Function that takes a pointer // to a function int invoke(int x, int y, int (*func)(int, int)) { return func(x, y); } // Driver Code int main() { // Pass pointers to add & multiply // function as required cout << "Addition of 20 and 10 is "; cout << invoke(20, 10, &add) << '\n'; cout << "Multiplication of 20" << " and 10 is "; cout << invoke(20, 10, &multiply) << '\n'; return 0; }
输出:
20 和 10 加起来是 30
20 和 10 相乘是 200
2. 使用 std::function<>
在C++ 11中,有一个std::function<> 模板类,允许将函数作为对象传递。std::function<> 的对象可以 按如下方式创建。
std::function<return_type(arg1_type, arg2-type...)> obj_name
// 该对象可用于调用如下函数
return_type catch_variable = obj_name(arg1, arg2);
例子:
C++
// C++ program to demonstrate the passing // of functions as an object parameter #include <functional> #include <iostream> using namespace std; // Define add and multiply to // return respective values int add(int x, int y) { return x + y; } int multiply(int x, int y) { return x * y; } // Function that accepts an object of // type std::function<> as a parameter // as well int invoke(int x, int y, function<int(int, int)> func) { return func(x, y); } // Driver code int main() { // Pass the required function as // parameter using its name cout << "Addition of 20 and 10 is "; cout << invoke(20, 10, &add) << '\n'; cout << "Multiplication of 20" << " and 10 is "; cout << invoke(20, 10, &multiply) << '\n'; return 0; }
输出:
20 和 10 加起来是 30
20 和 10 相乘是 200
例子:
C++
// C++ program to pass the function as // parameter as a lambda expression #include <functional> #include <iostream> using namespace std; // Function that takes a pointer // to a function int invoke(int x, int y, function<int(int, int)> func) { return func(x, y); } // Driver Code int main() { // Define lambdas for addition and // multiplication operation where // we want to pass another function // as a parameter // Perform Addition cout << "Addition of 20 and 10 is "; int k = invoke(20, 10, [](int x, int y) -> int { return x + y; }); cout << k << '\n'; // Perform Multiplication cout << "Multiplication of 20" << " and 10 is "; int l = invoke(20, 10, [](int x, int y) -> int { return x * y; }); cout << l << '\n'; return 0; }
输出:
20 和 10 加起来是 30
20 和 10 相乘是 200
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。