初始化一个大小定义为extern const的数组时遇到问题.我一直遵循以下规则:全局变量应该在头文件中声明为extern,并且它们的相应定义应该在其中一个实现文件中,以避免变量重新声明错误.这种方法工作正常,直到我必须初始化一个数组,其大小被定义为extern const.我得到一个错误,预计会有一个常量表达式.但是,如果我尝试为const变量赋值,则编译器会正确地抱怨不能将值赋给常量变量.这实际上证明了编译器确实将变量视为常量.当我尝试声明一个相同大小的数组时,为什么会报告错误?
没有使用#define有什么方法可以避免这种情况吗?我也想知道这个错误的原因.
Package.h:
#ifndef PACKAGE_H
#define PACKAGE_H
extern const int SIZE;
#endif
Run Code Online (Sandbox Code Playgroud)
Package.cpp:
#include "Package.h"
const int SIZE = 10;
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)