c++ - 回调函数 : difference between void(*func)(int) and void(func)(int)

标签 c++ c function callback

假设我有一个函数:

void foo (int i){
    cout << "argument is: " << i << endl;
}

我将这个函数传递给:

void function1 (void(callback)(int), int arg){
    callback(arg);
}

void function2 (void(*callback)(int), int arg){
    callback(arg);
}

这两个函数是一样的吗?两者有什么区别吗?

最佳答案

规则是,在函数的参数列表中,声明为具有函数类型的参数被调整为具有指向函数类型的指针(类似地,可能更广为人知的是,声明为类型为“数组T”调整为“指向 T 的指针”类型。允许在声明符中使用冗余括号,但会被忽略。

因此,在

void function1 (void(callback)(int), int arg);
void function2 (void (*callback)(int), int arg);
void function3 (void callback(int), int arg);

这三个函数的第一个参数具有完全相同的类型 - “指向返回 void(int) 函数的指针”。

关于c++ - 回调函数 : difference between void(*func)(int) and void(func)(int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25953542/

相关文章:

c - 从标准输入读取变量输入

javascript - 在 JavaScript 中,我不明白下面代码的输出

mysql - mysql中多边形和点之间的距离

C++ 列表,获取列表中的元素数?

c++ - 将 char 乘以整数 (c++)

c++ - 函数和/或类的包可访问性

c - 输出的奇怪行为

c++ - 管理输入 Mouse with DirectX DirectInput

c - 一行输入多个int,返回int的个数

python - 使用 "if else"语句和命名常量在 Python 中创建函数