c ++ void函数作为其他函数的参数
c++ void function as parameter for other function
我不明白为什么这个使用 int 函数和参数的代码可以正常工作,但是另一个使用 void 函数和没有参数的代码却不能:
第一个:
#include <iostream>
int Add(int x, int y)
{
return x+y;
}
int operation(int x, int y, int (*function)(int, int))
{
return function(x, y);
}
int main()
{
std::cout << operation(1, 4, &Add) << std::endl;
return 0;
}
第二个:
#include <iostream>
void a()
{
std::cout << "something" << std::endl;
}
void b(void (*function))
{
function();
}
int main()
{
b(&a);
return 0;
}
在您的第一个示例中,您不需要获取 Add() 的地址。按名称传递函数,不带参数,将自动获取地址。
std::cout << operation(1, 4, Add) << std::endl;
在你的第二个例子中,你忘记了函数指针中的括号:
void b(void (*function)(/* these brackets were missing */))
{
传递给b时也不需要取a的地址,因为引用一个没有参数的函数会取它的地址:
int main()
{
b(a);
return 0;
}
我不明白为什么这个使用 int 函数和参数的代码可以正常工作,但是另一个使用 void 函数和没有参数的代码却不能:
第一个:
#include <iostream>
int Add(int x, int y)
{
return x+y;
}
int operation(int x, int y, int (*function)(int, int))
{
return function(x, y);
}
int main()
{
std::cout << operation(1, 4, &Add) << std::endl;
return 0;
}
第二个:
#include <iostream>
void a()
{
std::cout << "something" << std::endl;
}
void b(void (*function))
{
function();
}
int main()
{
b(&a);
return 0;
}
在您的第一个示例中,您不需要获取 Add() 的地址。按名称传递函数,不带参数,将自动获取地址。
std::cout << operation(1, 4, Add) << std::endl;
在你的第二个例子中,你忘记了函数指针中的括号:
void b(void (*function)(/* these brackets were missing */))
{
传递给b时也不需要取a的地址,因为引用一个没有参数的函数会取它的地址:
int main()
{
b(a);
return 0;
}