是否可以转发声明一个静态数组 [英] Is it possible to forward declare a static array
问题描述
我需要将静态数组放入.cpp文件中。这个数组只用在这个.cpp中,所以我想声明它静态。数组定义相当大,所以我自然要转发声明它。
I need to put a static array into a .cpp file. This array is only used in this .cpp so I want to declare it static. The array definition is quite big, so naturally I want to forward declare it.
static int bigIntArray[5000];
/* other code using bitIntArray */
static int bigIntArray[5000] = {
0x00, 0x9900, 0xffee,
...
};
VC 9.0提供错误:error C2086:'int bigIntArray [5000]':redefinition
VC 9.0 gives an error: error C2086: 'int bigIntArray[5000]' : redefinition
如果我将static改为extern,问题就消失了,但我不喜欢这个解决方案。
If I change 'static' to 'extern', the problem goes away but I do not like this solution.
为什么我不能转发声明一个静态变量?这是C ++标准所要求的吗?
Why I can not forward declare a static variable? Is this required by the C++ standard?
推荐答案
有回答一个稍微不同的问题的风险),您可能想要使用带有extern的匿名命名空间。这会阻止其他翻译单元访问数组。
At the risk of answering a slightly different question (yours was answered well by Charles Bailey), you might want to use an anonymous namespace with an extern. This prevents other translation units from accessing the array.
namespace {
extern int bigIntArray[5000];
}
// Code that uses bigIntArray
namespace {
int bigIntArray[5000] = { ... };
}
这可能符合您的需要。
这篇关于是否可以转发声明一个静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!