在 C++ Primer(第 4 版)中有如下部分:
与其他变量不同,除非另有说明,否则const
在全局范围内声明的变量对于定义对象的文件是本地的。该变量仅存在于该文件中,其他文件无法访问。我们可以const
通过指定它是使一个对象在整个程序中可访问extern
:
// file_1.cc
// defines and initializes a const that is accessible to other files
extern const int bufSize = fcn();
// file_2.cc
extern const int bufSize; // uses bufSize from file_1
// uses bufSize defined in file_1
for (int index = 0; index != bufSize; ++index)
// ...
这是我尝试过的:
// file_1.cc
// defines and initializes a const that is accessible to other files
const int bufSize = fcn();
// file_2.cc
extern const int bufSize; // uses bufSize from file_1
// uses bufSize defined in file_1
for (int index = 0; index != bufSize; ++index)
// ...
它也没有问题。所以我的问题是:
变量是const
文件的本地变量还是只是一个错误?
非常感谢。