分享

验证: 默认情况下, const变量仅在当前文件范围内有效

 torony 2016-01-16

       在本文中, 我们来验证一下:默认情况下, const变量仅在当前文件范围内有效。


       实验一: 

      main.cpp内容如下:

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. extern int n;  
  5.   
  6. int main()  
  7. {  
  8.     cout << n << endl;  
  9.   
  10.     return 0;  
  11. }  
      test.cpp的内容如下:

  1. int n = 100;  
      编译运行一下, 程序ok.


      实验二:

      main.cpp

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. extern const int n;  
  5.   
  6. int main()  
  7. {  
  8.     cout << n << endl;  
  9.   
  10.     return 0;  
  11. }  
      test.cpp

  1. const int n = 100;  
     程序编译错误, 为什么呢? 因为const形式的n只在test.cpp中有效, 那怎么解决这个问题呢? 我们继续看。


      实验三:

     main.cpp

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. extern const int n;  
  5.   
  6. int main()  
  7. {  
  8.     cout << n << endl;  
  9.   
  10.     return 0;  
  11. }  
     test.cpp

  1. extern const int n = 100;  
     程序编译运行ok.  外部要能访问test.cpp中的const形式的n, 必须在test.cpp中定义的时候用extern限定。




    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多