变量的前向声明?
我有一些 C 代码必须移植到 C++。代码有一个结构
struct A {
...
struct A * myPtr;
}
现在两个全局数组被声明并初始化如下:
//Forward declaration of Unit
struct A Unit[10];
struct A* ptrUnit[2] = { Unit, Unit+7 };
struct A Unit[10] = { { .., &ptrUnit[0] },
... };
现在虽然这在 C 中工作正常,但在 C++ 中却给出了错误(变量重新声明)。 C++ 中不允许向前声明变量吗?
I have some C code that I have to port to C++. The code has a structure
struct A {
...
struct A * myPtr;
}
And now two global arrays are declared and initialized like this:
//Forward declaration of Unit
struct A Unit[10];
struct A* ptrUnit[2] = { Unit, Unit+7 };
struct A Unit[10] = { { .., &ptrUnit[0] },
... };
Now while this works fine in C, it gives an error in C++ (variable redeclared).
Aren't variables allowed to be forward-declared in C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
struct A Unit[10]
不是变量的前向声明。术语“前向声明”通常指非定义声明,而struct A Unit[10]
是定义。因此,在您的代码中,您在同一源文件中多次定义Unit
。在 C 语言中这是允许的,因为在 C 语言中没有初始化器的定义是暂定定义。它们可能在同一个翻译单元中出现多次。在 C++ 中,没有暂定定义这样的东西。在 C++ 中,多重定义始终是非法的。如果您想要变量的真正前向声明,则必须使用关键字
extern
这在 C 和 C++ 中都适用。然而,作为一个副作用,这将产生
Unit
外部 链接。如果您需要一个具有内部链接的变量,那么您在 C++ 中就不那么幸运了,因为在 C++ 中不可能前向声明具有内部链接的变量。同时,C 中的暂定定义仍将帮助您实现这一目标。struct A Unit[10]
is not a forward declaration of a variable. The term "forward declaration" normally refers to non-defining declarations, whilestruct A Unit[10]
is a definition. So in your code you are definingUnit
multiple times in the same source file. In C language it is allowed, since in C definitions without an initializer are tentative definitions. They may occur many times in the same translation unit. In C++ there's no such thing as tentative definition. In C++ multiple definitions are always illegal.If you want a genuine forward declaration for a variable, you have to use the keyword
extern
This will work in both C and C++. However, as a side effect, this will give
Unit
external linkage. If you need a variable with internal linkage, then you are out of luck in C++, since in C++ it is not possible to forward-declare a variable with internal linkage. Meanwhile, in C tentative definitions will still help you to achieve that.在 C++ 中,变量声明必须以
extern
为前缀:(请注意,在 C++ 中,您可以省略前导的
struct
。)In C++, a variable declaration must be prefixed with
extern
:(Note that in C++ you can omit the leading
struct
.)C 允许暂时声明变量(我猜)。 C++ 没有。一旦定义了“Unit”,就不能在同一范围内重新定义它
C allows variables to be tenatively declared (I guess). C++ does not. Once 'Unit' has been defined, it cannot be redefined in the same scope
使
Unit
成为一个返回对 A[10] 的引用的函数,并使实际数组成为函数中的静态变量。Make
Unit
a function that returns a reference to to A[10] and have the actual array be a static variable in the function.