“数组边界不是整数常量”在类中定义数组大小时,使用 const 数组的元素
#ifndef QWERT_H
#define QWERT_H
const int x [] = {1, 2,};
const int z = 3;
#endif
#include <iostream>
#include "qwert.h"
class Class
{
int y [x[0]]; //error:array bound is not an integer constant
int g [z]; //no problem
};
int main ()
{
int y [x[0]]; //no problem
Class a_class;
}
我不明白为什么这不起作用。其他遇到此问题的人似乎正在尝试动态分配数组。非常感谢任何帮助。
#ifndef QWERT_H
#define QWERT_H
const int x [] = {1, 2,};
const int z = 3;
#endif
#include <iostream>
#include "qwert.h"
class Class
{
int y [x[0]]; //error:array bound is not an integer constant
int g [z]; //no problem
};
int main ()
{
int y [x[0]]; //no problem
Class a_class;
}
I can't figure out why this doesn't work. Other people with this problem seem to be trying to dynamically allocate arrays. Any help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
x 是 const(显然 z 也是),但 x[0] 不是常量表达式。类定义中的数组声明必须具有常量大小说明符。
考虑一下这个问题;如果类在编译时包含未知大小的数组,您如何期望 sizeof 运算符来评估类的大小?
x is const (as is z obviously), but x[0] is not a constant expression. Array declarations in a class definition must have constant size specifiers.
Consider this for a moment; how would you expect the sizeof operator to evaluate the size of your class if it contains an array of unknown size at compile time?
主要版本之所以有效,是因为您的编译器具有允许可变长度数组的扩展。在C++03中数组访问不能是常量表达式,即使数组和索引都是常量表达式,这就是错误的根源。
The main version works because your compiler has an extension to allow for variable length arrays. Array accesses cannot be constant expressions in C++03, even if the array and the index are both constant expressions, which is the source of the error.
数组的大小必须是常量表达式。我不认为数组中的常量元素符合这样的条件。
main() 中工作的版本可能是由于编译器扩展所致。
The size of an array must be a constant expression. I don't believe that constant elements in an array qualify as such.
The version in main() working is probably due to a compiler extension.