如何阅读这个声明 int (*(*f2)(int n))[3];

问题描述

我从 https://en.cppreference.com/w/cpp/language/scope 得到了这个声明,但即使下面有评论也不知道如何解析这个声明。

我的问题是 如何解析声明语句(我将其视为指向函数协议的函数指针,例如“int[3] foo(int n)”或“int foo(int n)[3] --- 它们在 C++ 中是非法的) ? 那么,我怎样才能构造一个具体的函数来分配给这个函数指针呢?谢谢。

const int n = 3;
int (*(*f2)(int n))[n]; // OK: the scope of the function parameter 'n'
                        // ends at the end of its function declarator
                        // in the array declarator,global n is in scope
// (this declares a pointer to function returning a pointer to an array of 3 int

解决方法

它是一个指向函数的指针,该函数接受一个 int 并返回一个指向大小为 3 的 int 数组的指针。

所有评论都是说这里有两个 n 标识符。 [n](在数组声明器中)使用的是 const int 3,而不是函数的参数(在函数声明器中)。

从中间开始,每个段都作为 ... 包含在随后的项目符号中:

  • f2 是一个指针,(*f2)
  • 它是一个指向一个函数的指针,该函数采用一个整数 ...(int)
  • 它返回一个指向大小为 3 的 int 数组 int (*...)[3] 的指针。

您可以按照以下完整程序为其形成一个具体的函数,该程序输出第一个元素42

#include <iostream>

const int n = 3;
int (*(*f2)(int n))[n];

int (*g2(int))[n] {
    static int x[::n] = { 42 }; // Use outer n,not the parameter.
    return &x;                  //   since C++ has no VLAs. This
                                //   means parameter is not actually
                                //   needed in this test case,though
                                //   it may be in more complicated
                                //   tests.
}

int main() {
    f2 = &g2;                       // Assign concrete function to pointer.
    auto y = f2(3);                 // Call via pointer,get array.
    std::cout << *(y[0]) << '\n';   // Deref first element to get 42.
}

话虽如此,我还是会很好奇我的一位同事是否提交了类似的内容进行代码审查,至少没有大量注释解释。尽管经验丰富的开发人员可能能够解决这个问题,但经验不足的开发人员可能会遇到麻烦。

而且,事实上,即使是经验丰富的开发人员也不应该解决它,特别是考虑到我花了几分钟时间。

C++ 有一个非常有表现力的类型系统,它可以很容易地分部分构建这样的东西,所以你不必经历偏头痛试图解决它。对于这样的事情,我会使用 std::vector(或 std::array),除非有一个令人信服的案例,因为更基本的类型会增加复杂性。

,

您可以为 pointer to an array of 3 int

创建一个类型
typedef int (*array_with_size_n)[n];

然后将其用作返回类型

const int n = 3;
int (*(*f2)(int n))[n];
int arr[n];
array_with_size_n func(int n)
{
  return &arr;
}
int main()
{
   f2 = &func;
   return 0;
}