I want to ask about pointer in C++
I have some simple code:
int add(int a, int b){
return开发者_C百科 a+b;
}
int runner(int x,int y, int (*functocall)(int, int)){
return (*functocall)(x,y);
}
now, suppose I call those functions using this way :
cout<<runner(2,5,&add);
or maybe
cout<<runner(2,5,add);
is there any difference? because when I tried, the result is the same and with no error.
Thanks a lot
Function will be implicitly casted to a pointer according to C++ Standard (4.3/1). There is no difference. However this conversion never applies to nonstatic member functions. For them you should explicitly write &
.
There is no difference. For consistency with other ways of getting a pointer you can use &
, but the name by itself would have no other meaning so it is assumed to mean "get the address".
It's very similar to array variable names acting as the address of the first element of the array.
No, in this particular case there is no difference. Either one gives you the address of the function.
Note, however, that in C++, getting a pointer to a member function requires that you use the '&' operator.
Notice that you can have references to functions
int runner(int x,int y, int (&functocall)(int, int)){
return functocall(x,y);
}
Now calling it with &add
won't work anymore because you try to bind a function reference to a pointer instead of to a function. Sometimes this shines through when using templates
template<typename T>
int runner(int x,int y, T &functocall, T otherfunc){
return functocall(x,y) + otherfunc(y, x);
}
Now calling it with runner(10, 20, add, add)
will fail because T
is tried to be deduced to both a function pointer and a function type (no decay to a pointer is done when passing to a reference parameter!).
I believe the second call automatically resolves to the first call in the compiler...
it is because there is no such object (in terms of expressions) as function, there are only pointers to functions. When you want to pass function to your function the only thing you can actually pass is pointer, so compiler does this cast for you
精彩评论