我想知道这两个函数(fun
和fun2
)有什么区别我知道fun2
是函数指针,但是 fun
是什么?这是否相同,因为还传递了作为函数名的指针?
#include <iostream>
void print()
{
std::cout << "print()" << std::endl;
}
void fun(void cast())
{
cast();
}
void fun2(void(*cast)())
{
cast();
}
int main(){
fun(print);
fun2(print);
}
最佳答案
Is that the same because there is also passing by pointer which is function name ?
是的。这是从C继承而来的,纯粹是为了方便。 fun 和 fun2 都接收一个类型为“void ()”的指针。
这种便利是允许存在的,因为当您调用带括号的函数时,没有歧义。如果您有带括号的参数列表,您必须调用一个函数。
如果您禁用编译器错误,以下代码也将起作用:
fun4(int* hello) {
hello(); // treat hello as a function pointer because of the ()
}
fun4(&print);
关于c++ - 函数指针 - 2 个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33676126/