c ++函数(带体)作为参数

Hei*_*ich 2 c++ function argument-passing

我想传递一个函数作为参数.我知道你可以传递一个函数指针,就像我的例子中的第一个测试一样,但是可以像我的第二次测试一样传递一个hold函数(不是指针)吗?

#include <iostream>

using namespace std;


/* variable for function pointer */
void (*func)(int);

/* default output function */
void my_default(int x) {
    cout << "x =" << "\t" << x << endl << endl;
}


/* entry */
int main() {
    cout << "Test Programm\n\n";

    /* 1. Test - default output function */
    cout << "my_default\n";
    func = &my_default;   // WORK! OK!
    func(5);

    /* 2. Test - special output function 2 */
    cout << "my_func2\n";
    func =  void my_func1(int x) {
            cout << "x =" << "  " << x << endl << endl;
        };   // WON'T WORK! FAILED!
    func(5);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 6

在C++ 11中,您可以传递lambda:

func = [](int x) {  cout << "x =" << "  " << x << endl << endl; };
Run Code Online (Sandbox Code Playgroud)

编辑:lambdas可以返回值:

func = [](int x)->int{  cout << "x =" << "  " << x << endl << endl; return x; };
Run Code Online (Sandbox Code Playgroud)

  • 并且只包含一个return语句的lambdas可以省略` - > type`以使其更简单:`[](int x){return x*x; }` (2认同)