const常量用extern声明定义的问题(extern变量不能在使用类里初始化)

test.h

 

[cpp] view plain copy
 
  1. #ifndef TEST_H_  
  2. #define TEST_H  
  3.   
  4. //常量声明和定义采取这种方法即可  
  5. const int a = 20;  //不报错,因为const变量链接属性默认是内部链接,就算两个cpp文件都引用了该.h文件,也不会出现重复定义的错误。  
  6.   
  7. //extern const int b = 20;//这个报错,因为加上extern之后链接属性就是外部链接了,当被多个.cpp文件包含时则会导致重定义。  
  8.   
  9. extern const int  b;    //改成这个不报错,所以用extern只声明变量,而在test.cpp定义这个变量  
  10.   
  11. #endif  

 

test.cpp

 

[cpp] view plain copy
 
  1. #include "test.h"  
  2.   
  3. const int b = 3;//定义b,如果只在test.h里用extern声明了,而没有定义,那么因为在main.cpp使用了变量b,就会出现链接错误  

 

main.cpp

 

[cpp] view plain copy
 
  1. #include "test.h"  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     cout << b << endl;  
  8.   
  9.     return 0;  
  10. }  

http://blog.csdn.net/bladeandmaster88/article/details/64906841

posted @ 2018-02-09 20:58  findumars  Views(530)  Comments(0Edit  收藏  举报