是否可以在C++中将函数作为参数传递?

And*_*een 0 c++ parameters function

有没有办法在C++ 中将函数作为参数传递,比如函数在C中作为参数传递的方式?我知道可以使用函数指针将函数作为参数传递给C,我想知道在C++中是否可以实现相同的功能.

Nik*_* C. 7

你可以像在C中那样做.但你也可以用C++方式(C++ 11,确切地说):

// This function takes a function as an argument, which has no
// arguments and returns void.
void foo(std::function<void()> func)
{
    // Call the function.
    func();
}
Run Code Online (Sandbox Code Playgroud)

你可以将正常的函数传递给foo()

void myFunc();
// ...
foo(myFunc);
Run Code Online (Sandbox Code Playgroud)

但你也可以传递一个lambda表达式.例如:

foo([](){ /* code here */ });
Run Code Online (Sandbox Code Playgroud)

您还可以传递一个函数对象(一个重载()运算符的对象.)通常,您可以传递可以使用()运算符调用的任何内容.

如果您改为使用C方式,那么唯一可以传递的是普通函数指针.