使用静态常量 + const 作为数组边界
我正在做这样的事情
Class.hpp:
class Class {
private:
static const unsigned int arraySize;
int ar[arraySize+2];
};
Class.cpp:
#include <Class.hpp>
const unsigned int arraySize = 384;
编译器(q++,基于 g++ 的 QNX 操作系统的 c++ 编译器)给了我 error: arraybound is not an integer Constant
while编译包含 Class.hpp
的单元(不是在编译 Class.cpp 时)。
为什么这不起作用?我知道静态 const 成员可以用作数组绑定,由 C++ 标准保证(请参阅此 anwser)。但为什么编译器没有将 static const + const
的结果视为常量呢?
I'm doing something like this
Class.hpp:
class Class {
private:
static const unsigned int arraySize;
int ar[arraySize+2];
};
Class.cpp:
#include <Class.hpp>
const unsigned int arraySize = 384;
The compiler (q++, a c++ compiler for the QNX OS based on g++) gives me error: array bound is not an integer constant
while compiling a unit including Class.hpp
(not while compiling Class.cpp).
Why isn't that working? I know that a static const member can be used as an array bound, guaranteed by the C++ standard (see this anwser). But why doesn't the compiler see the result of static const + const
as a constant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是好的代码,应该被编译器接受:
如果没有,你的编译器就坏了。
但是,如果将实际常量从头文件移至选定的翻译单元,则会导致代码无效。
这是因为在编译时无法仅根据标头中的可用数据确定
Class
对象的大小。这不是完全正确的原因,但是沿着这些思路进行推理有助于理解诸如此类的编译错误。为了避免犯这样的错误,您可以将
static const int
替换为enum
,例如This is good code which should have been accepted by the compiler:
and if it isn't, your compiler is broken.
However, if you move actual constant out of the header file to selected translation unit, that invalidates the code.
This is because the size of your
Class
object cannot be determined at compile time from the data available in the header alone. This is not exactly right reason, but reasoning along these lines helps to understand compilation errors such as this.To avoid making such mistakes, you can replace
static const int
with anenum
, e.g.正如评论所说,我很惊讶这实际上可以在 gcc 上编译。由于
384
不在头文件中,因此其他编译单元不知道Class
的大小。在某些编译单元中,这可能并不重要,具体取决于它们如何/是否使用Class
,但我无法想象这种编译:您需要在 .hpp 中包含:
..,因为它在您链接到的OP 此处。
I'm surprised this actually compiles on gcc, as a comment says. Since the
384
isn't in the header file, the size of theClass
is not known to other compilation units. It might not matter in some compilation units depending on how/if they are usingClass
, but I can't imagine this compiling:You need to have in your .hpp:
.. as it is in the OP that you link to here.