另一个函数内的函数前向声明

发布于 2025-01-03 16:01:11 字数 634 浏览 2 评论 0原文

代码在前:

void foo(int x)
{
    void bar(int);  //is this forward-decl legal?
    bar(x);
}

void bar(int x)
{
    //do stuff
}

在上面的代码中,foo调用bar,通常我将bar的forward-decl放在foo<之外/code>,像这样:

void bar(int);
void foo(int x) 
{
    bar();
}

首先,我认为把 bar 的forward-decl 放在 foo 里面是可以的,对吧?

其次,考虑一下,如果 bar 是一个像这样的 static 函数:

static void bar(int x)
{
    //do stuff
}

那么我应该如何前向声明它?我的意思是forward-decl 应该采用还是省略static

Code goes first:

void foo(int x)
{
    void bar(int);  //is this forward-decl legal?
    bar(x);
}

void bar(int x)
{
    //do stuff
}

In the code above, foo calls bar, usually I put the forward-decl of bar outside of foo, like this:

void bar(int);
void foo(int x) 
{
    bar();
}

First, I think it's OK to put bar's forward-decl inside foo, right?

Second, consider this, if bar is a static function like this:

static void bar(int x)
{
    //do stuff
}

Then how should I forward-declare it? I mean should the forward-decl take or omit the static?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

婴鹅 2025-01-10 16:01:11
  1. 是的,在另一个函数中放置前向声明是合法的。那么它只能在该函数中使用。并且将使用您放入其中的函数的名称空间,因此请确保匹配。

  2. 该标准规定:“给定实体的连续声明所暗示的联系应一致。” (第 7.1.2 节)。所以是的,原型也必须是静态的。但是,看起来根本不允许将静态链接函数的原型放入另一个函数中。 “块内不能有静态函数声明”(同一节)。

  1. Yes it's legal to put a forward-declaration inside another function. Then it's only usable in that function. And the namespace of the function you put it inside will be used, so make sure that matches.

  2. The Standard says: "The linkages implied by successive declarations for a given entity shall agree." (section 7.1.2). So yes, the prototype must be static also. However, it doesn't look like putting a prototype of a static linkage function inside another function is allowed at all. "There can be no static function declarations within a block" (same section).

亢潮 2025-01-10 16:01:11

是的,将前向声明放在函数内部就可以了。只要编译器在调用该函数之前已经看到它,它在哪里并不重要。您也可以在命名空间中前向声明函数。然而,原型仅限于它们所处的范围:

int blah() {
    { void foo(); }

    foo(); // error: foo not declared
}

其次,你只需要将static放在prototype上,否则编译器会抱怨bar code> 被声明为 extern(所有原型都隐式地 extern,除非它们被例如 static 显式标记)。请注意,静态函数原型不能出现在函数内部。

Yes, it is fine to put the forward declaration inside the function. It doesn't matter where it is as long as the compiler has seen it before you call the function. You can forward-declare functions in namespaces as well. However, prototypes are limited to the scope they are in:

int blah() {
    { void foo(); }

    foo(); // error: foo not declared
}

Secondly, you only need to put static on the prototype, else the compiler will complain about bar being declared extern (all prototypes are implicitly extern unless they are explicitly marked otherwise by e.g. static). Note that static function prototypes cannot appear inside a function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文