首先,有一点需要明确,就是const对象默认为文件的局部变量。通常,在全局作用域定义的非const变量,它在整个程序中都可以访问,例如
//file1.cpp
int counter;
//file2.cpp
extern int counter;
cout << counter <<endl;
在file1.cpp中定义全局变量counter, 在file2.cpp中可以访问;
但是,对于const全局变量,这样做就会错误,例如
//file1.cpp
const int counter = 0;
//file2.cpp
extern const int counter;
count << counter <<endl;
这个例子,在链接时会报找不到conuter的错误。原因是因为const对象是文件的局部变量,也就是说counter仅在file1.cpp可见。
通过指定const变量为extern, 就可以在整个程序中访问const 对象,如
//file1.cpp
extern const int counter = 0;
//file2.cpp
extern const int counter;
<pre name="code" class="cpp">count << counter <<endl<span style="font-family: Arial, Helvetica, sans-serif;">;</span>