假设我有一个名为的函数
这个函数应该怎么正确地调用?我需要设置什么才能让它正常工作?
void funct2(int a) {
}
void funct(int a, (void)(*funct2)(int a)) {
;
}
这个函数应该怎么正确地调用?我需要设置什么才能让它正常工作?
void funct2(int a) {
}
void funct(int a, (void)(*funct2)(int a)) {
;
}
通常出于可读性的考虑,您可以使用typedef来定义自定义类型,如下所示:
typedef void (* vFunctionCall)(int args);
当定义此typedef时,您希望函数原型的返回参数类型(在本例中为void类型)作为typedef标识符的前缀,并将原型参数跟随其后(在本例中为"int args")。
在将此typedef用作另一个函数的参数时,您将定义您的函数如下(此typedef几乎可以像任何其他对象类型一样使用):
void funct(int a, vFunctionCall funct2) { ... }
然后像普通函数一样使用,如下:
funct2(a);
那么一个完整的代码示例会像这样:
typedef void (* vFunctionCall)(int args);
void funct(int a, vFunctionCall funct2)
{
funct2(a);
}
void otherFunct(int a)
{
printf("%i", a);
}
int main()
{
funct(2, (vFunctionCall)otherFunct);
return 0;
}
并且会打印出:
2
using vFunctionCall = void (*)(int args);
。甚至更好的选择是使用std::function。 - Frederico Pantuzzastd::function<void(int)>
比 void (*)(int args)
做的事情 多得多,因此对于平台来说更难进行优化。 - Caleth#include <functional>
#include <iostream>
void displayMessage(int a) {
std::cout << "Hello, your number is: " << a << '\n';
}
void printNumber(int a, std::function<void (int)> func) {
func(a);
}
int main() {
printNumber(3, displayMessage);
return 0;
}
输出:
Hello, your number is: 3
using namespace std
,因为这是一种不好的编程习惯:https://dev59.com/D3M_5IYBdhLWcg3wQQ3w?rq=1 - Overt_Agentstd::function
,它类似于函数类型,例如在函数式语言中的类型int -> double
。它实际上不是一个类型,而是一个类模板,类实例可以持有可调用的函数,但在使用时,将其视为函数类型是很有用的。int
并返回double
:double halve(int x)
{
return x / 2;
}
std::function<double(int)> f = halve; // can store a lambda too
double call_f(std::function<double(int)> f, int x)
{
return f(x);
}
#include <iostream>
#include <functional>
int Add(int a, int b)
{
return a + b;
}
int Mul(int a, int b)
{
return a * b;
}
int Power(int a, int b)
{
while (b > 1)
{
a = a * a;
b -= 1;
}
return a;
}
int Calculator(std::function<int(int, int)> foo, int a, int b)
{
return foo(a, b);
}
int main()
{
cout << std::endl
<< "Sum: " << Calculator(Add, 1, 2);
cout << std::endl
<< "Mul: " << Calculator(Mul, 1, 2);
cout << std::endl
<< "Power: " << Calculator(Power, 5, 2);
return 0;
}
请检查这个
typedef void (*funct2)(int a);
void f(int a)
{
print("some ...\n");
}
void dummy(int a, funct2 a)
{
a(1);
}
void someOtherMehtod
{
callback a = f;
dummy(a)
}
funct2
隐藏在funct
中,因此你必须完全限定funct2
才能直接从funct
内部调用它。 - CB Bailey