gpt4 book ai didi

c++ - 备用函数语法/函数原型(prototype)?

转载 作者:行者123 更新时间:2023-11-30 05:32:55 24 4
gpt4 key购买 nike

我一直在 C++ 中使用函数指针,我一直将它们声明为 void (*function)(void)。这就是我最初在教程和 how tutorials still teach it 中看到的方式.

但是今天,我在阅读维基百科关于高阶函数的文章时发现了一个使用替代语法的示例,其中 * 和函数指针变量/类型名称周围的括号不存在,如所见here .

我测试了 void function(void) 形式是否适用于变量、参数和 typedef。它不适用于变量,但它适用于参数和类型定义,没有明显的变化,实际上可以与标准函数指针语法互换。

我进一步挖掘并找到了 an SO question这似乎暗示它是“函数原型(prototype)”的语法而不是函数指针。然而wikipedia's explanation of function prototypes听起来很像预声明函数。

我为我的问题的广泛范围道歉,但是这个语法到底是什么?

  • 它是否定义了“函数原型(prototype)”或函数指针?
  • 如果是函数原型(prototype),就是函数指针和函数原型(prototype)相同还是它们只是表现相同?
  • 如果不是函数原型(prototype),是否表示“函数原型(prototype)”只是函数的预先声明吗?
  • 如果这个语法等同于标准函数指针语法,为什么更冗长(并且可以说更难阅读)的语法更常见的教学形式?
  • 语法是否产生不同的结果/具有不同的含义我怎么没注意到?

最佳答案

不,它们不一样。数组和指针不一样只是因为您可以将 int A[] 写为参数。具体规则可参见n4567标准草案:

§8.3.5/5 ... After determining the type of each parameter, any parameter of type "array of T" or of function type T is adjusted to be "pointer to T". ...

后面会更明确:

§13.2/3 ...

  • Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5). [ Example:

     void h(int());
    void h(int (*)()); // redeclaration of h(int())
    void h(int x()) { } // definition of h(int())
    void h(int (*x)()) { } // ill-formed: redefinition of h(int())

    end example ] ...

该规则也适用于其他地方(不是完整列表):

  • 非类型模板参数
  • 模板参数推导
  • 异常处理程序

关于c++ - 备用函数语法/函数原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34960981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com