【问题标题】:how to read this declaration int (*(*f2)(int n))[3];如何阅读此声明 int (*(*f2)(int n))[3];
【发布时间】:2021-05-20 01:29:56
【问题描述】:

我从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

【问题讨论】:

  • 您可以使用像cdecl.org 这样的网站,它可以帮助将乱码 c 翻译成可读的英语
  • 找到写这篇文章的人,打他们的后脑勺。
  • @3Dave:后脑勺一记耳光不太可能对作者产生影响。他们显然是一名 C 开发人员,所以考虑到他们已经忍受了那种语言的痛苦,他们甚至不会感到这样的打击 :-) 而且,对于所有 C 开发人员,请不要生气。我曾经也是一个。但我恢复了:-)
  • @paxdiablo “嗨。我叫 Dave,是一名 C 程序员。” (人群回答)“嗨,戴夫。”

标签: c++ function-pointers


【解决方案1】:

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

所有评论都是说这里有 两个 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),除非有一个令人信服的案例,因为更多的基本类型会增加复杂性。

【讨论】:

  • 感谢 paxdiablo 的解释。现在事情已经变得相当清晰了。
  • 超酷!!! @paxdiablo。我只是好奇 C++ 的表现力如何,现在我的难题已经完美解决了。
【解决方案2】:

你可以为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;
}

【讨论】:

  • 感谢 Gaurav 的完美答案解决了我的困惑。只是一个后续问题:在代码中,我知道 typedef 工作正常。但是,必须使用 typedef 吗?有没有办法删除 typedef 并在函数定义中简单地声明相同的含义?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多