#ifndef QWERT_H
#define QWERT_H
const int x [] = {1, 2,};
const int z = 3;
#endif
#include <iostream>开发者_JAVA技巧;
#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.
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?
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.
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.
精彩评论