现在的位置: 首页 > 综合 > 正文

const 对象默认为文件的局部变量

2018年01月22日 ⁄ 综合 ⁄ 共 609字 ⁄ 字号 评论关闭

定义非const变量时候,他是可以被其它文件访问的。要使用该变量,只需在其他文件使用的地方使用extern Type_Name Variable_Name进行声明即可。而const变量不能这样,const变量默认是文件的局部变量。若要改变这种情况则需特别声明 
extern const type_Name Variable_Name进行声明。

incopy

  1.  * const.cpp 
  2.  * 
  3.  *  Created on: Nov 3, 2011 
  4.  *      Author: ubuntu 
  5.  */  
  6.   
  7. extern const int a = 78;  
  8. //如果a不声明为extern,则不能在test.cpp中不通过引入文件就访问不到他。  
  9.  int b=99;  
  10.   
  11.  


  1. #include<iostream>  
  2. //#include"const.cpp"  
  3.   
  4. using namespace std;  
  5.   

    1. int main()  
  6. {  
  7.     extern int b;  
  8.     extern const int a;  
  9.     cout << a +9<< endl;  
  10.     cout << b +89<< endl;  
  11.     return 0;  
  12. }  
头文件用于声明而不是用于定义。不过有三个例外。头文件可以定义类、值在编译时就已知道的const对象和inline函数。
【上篇】
【下篇】

抱歉!评论已关闭.