【问题标题】:Get confused with this declaration - int (*(*foo)(double))[3]对这个声明感到困惑 - int (*(*foo)(double))[3]
【发布时间】:2014-01-19 03:00:24
【问题描述】:

我迷失在这个宣言中 - int (*(*foo)(double))[3];

我的理解是这是一个大小为 3 的数组,其中元素是一个函数指针,采用 double 并返回指向 int 的指针。但是,正确的解释似乎是“指向函数的指针采用 double 并返回指向 3 int 数组的指针”。 返回的指向 3 个 int 数组的指针让我很困惑,因为 int[3] 相距甚远。

这是为什么呢?声明这种复杂变量的语法或规则是什么?

【问题讨论】:

标签: c++


【解决方案1】:

您只需从内到外阅读,记住后缀数组 ([]) 和函数“调用” (()) 绑定比前缀指针 (*) 更紧密:

      (*foo)              // foo is a pointer...
      (*foo)(double)      // to a function taking a double...
    (*(*foo)(double))     // returning a pointer...
    (*(*foo)(double))[3]  // to an array of 3...
int (*(*foo)(double))[3]; // ints

(要确定从哪里开始,您可能希望从外向内工作,但您需要从内向外阅读以按照常规顺序阅读声明。)

【讨论】:

    【解决方案2】:

    您可以使用"clockwise spiral rule"

          +----------------------------------+
          |  +---------------------------+   |
          |  |   +--------------------+  |   |
          |  |   | +----+             |  |   |
          |  |   | |+--+|             |  |   |
          |  |   | |^  ||             |  |   |
     int  (  *   ( *foo)( double      )  [3 ];
       |  ^  ^   ^ ^   ||             |  |   |
       |  |  |   | +---+|             |  |   |
       |  |  |   +------+             |  |   |
       |  |  +------------------------+  |   |
       |  +------------------------------+   |
       +-------------------------------------+  
    

    因此,标识符foo

    • 是一个指针
    • double 作为参数返回的函数
    • 指向
    • 的指针
    • 数组 3
    • int

    【讨论】:

    • 请参阅here 了解螺旋规则的优点。
    猜你喜欢
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    相关资源
    最近更新 更多