我想了解以下 2 个声明 f1
和 f2
之间的区别:
在 f1
中,我将参数声明为指向 void()
类型函数的指针,f2
声明与 有何不同>f1
?声明是否等效?在 main
中,我可以使用原型(prototype) void ()
的函数调用它们。我理解按值/指针/引用传递的概念,但是这些是函数,并不真正理解其中的区别。我不能“修改”在 f1
中作为参数传递的函数...谢谢!
PS:遇到众所周知的最令人烦恼的解析问题时遇到了这个问题:)
#include <iostream>
using namespace std;
void f1(void (*x)())
{
x();
}
void f2(void x())
{
x();
}
void g1()
{
cout << "Invoking f1(g1())" << endl;
}
void g2()
{
cout << "Invoking f2(g2())" << endl;
}
int main()
{
f1(g1);
f2(g2);
}
程序编译,输出为
Invoking f1(g1())
Invoking f2(g2())
最佳答案
在C和C++中,如果将函数参数声明为函数类型,其类型将调整为函数指针。
C99,§6.7.5.3/8
A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.
C++11,§8.3.5/5
... After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively...
因此,例如,在 C++ 中,我们可以将 f1
和 f2
的类型都写为 void(void(*)())
.
关于c++ - 指向函数参数与函数参数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23840421/