我想知道这两个函数( 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);
} 发布于 2015-11-12 17:02:54
这是否相同,因为也有传递指针,即函数名?
是。这是从C继承来的,完全是为了方便。fun和fun2都接受一个类型为"void ()“的指针。
这种方便是允许存在的,因为当您使用括号调用函数时,不存在歧义。如果您有括号大小的参数列表,则必须是调用函数。
如果禁用编译器错误,以下代码也将工作:
fun4(int* hello) {
hello(); // treat hello as a function pointer because of the ()
}
fun4(&print);http://c-faq.com/~scs/cclass/int/sx10a.html
https://stackoverflow.com/questions/33676126
复制相似问题