在本文中, 我们来验证一下:默认情况下, const变量仅在当前文件范围内有效。
实验一:
main.cpp内容如下:
- #include <iostream>
- using namespace std;
-
- extern int n;
-
- int main()
- {
- cout << n << endl;
-
- return 0;
- }
test.cpp的内容如下:
编译运行一下, 程序ok.
实验二:
main.cpp
- #include <iostream>
- using namespace std;
-
- extern const int n;
-
- int main()
- {
- cout << n << endl;
-
- return 0;
- }
test.cpp
程序编译错误, 为什么呢? 因为const形式的n只在test.cpp中有效, 那怎么解决这个问题呢? 我们继续看。
实验三:
main.cpp
- #include <iostream>
- using namespace std;
-
- extern const int n;
-
- int main()
- {
- cout << n << endl;
-
- return 0;
- }
test.cpp
- extern const int n = 100;
程序编译运行ok. 外部要能访问test.cpp中的const形式的n, 必须在test.cpp中定义的时候用extern限定。
|