另一个函数内的函数前向声明
代码在前:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,在另一个函数中放置前向声明是合法的。那么它只能在该函数中使用。并且将使用您放入其中的函数的名称空间,因此请确保匹配。
该标准规定:“给定实体的连续声明所暗示的联系应一致。” (第 7.1.2 节)。所以是的,原型也必须是静态的。但是,看起来根本不允许将静态链接函数的原型放入另一个函数中。 “块内不能有
静态
函数声明”(同一节)。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.
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 astatic
linkage function inside another function is allowed at all. "There can be nostatic
function declarations within a block" (same section).是的,将前向声明放在函数内部就可以了。只要编译器在调用该函数之前已经看到它,它在哪里并不重要。您也可以在命名空间中前向声明函数。然而,原型仅限于它们所处的范围:
其次,你只需要将
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:
Secondly, you only need to put
static
on the prototype, else the compiler will complain aboutbar
being declaredextern
(all prototypes are implicitlyextern
unless they are explicitly marked otherwise by e.g.static
). Note thatstatic
function prototypes cannot appear inside a function.