c++ - 指向函数参数与函数参数的指针?

标签 c++ pointers

我想了解以下 2 个声明 f1f2 之间的区别: 在 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++ 中,我们可以将 f1f2 的类型都写为 void(void(*)()).

关于c++ - 指向函数参数与函数参数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23840421/

相关文章:

c++ - const 基类的作用

c++ - WinAPI 获取对另一个应用程序控件的访问权限

c++ - 如何设置 Clang-Format Style Options 以在捕获之前不换行?

c++ - 'fprintf' 颜色格式包装器

c++ - 在列表中调用子对象

C sscanf : why is this segfaulting?

c++ - 无法理解核心文件分析的 GDB x 命令输出

c - C 中的指针、结构和函数

c - 在for循环中初始化变量(圆括号内)和在for循环之前初始化变量有什么区别吗?

pointers - 从非指针结构元素转到链表指针赋值