函数指针 - 2 个选项
Function Pointer - 2 options
我想知道这两个函数(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);
http://c-faq.com/~scs/cclass/int/sx10a.html
Why is using the function name as a function pointer equivalent to applying the address-of operator to the function name?
我想知道这两个函数(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);
http://c-faq.com/~scs/cclass/int/sx10a.html
Why is using the function name as a function pointer equivalent to applying the address-of operator to the function name?