我在初始化一个大小被定义为extern const的数组时遇到了问题。一直以来,我都遵循全局变量应该在头文件中声明为extern,对应的定义应该在某个实现文件中的规则,以避免变量重新声明错误。这种方法一直运行良好,直到我不得不初始化一个大小被定义为外部常量的数组。
我收到一个错误,说需要一个常量表达式。然而,如果我尝试为const变量赋值,编译器会正确地抱怨无法向常量变量赋值。这实际上证明了编译器将变量视为常量。那么当我尝试声明相同大小的数组时为什么会报错呢?
是否有任何方法可以避免这种情况,而不使用#define?我还想知道这个错误的原因。
Package.h:
#ifndef PACKAGE_H
#define PACKAGE_H
extern const int SIZE;
#endif
Package.cpp:
#include "Package.h"
const int SIZE = 10;
Foo.cpp:
#include "Package.h"
int main()
{
// SIZE = 5; // error - cannot assign value to a constant variable
// int Array[SIZE]; // error - constant expression expected
return 0;
}