定义非const变量时候,他是可以被其它文件访问的。要使用该变量,只需在其他文件使用的地方使用extern Type_Name Variable_Name进行声明即可。而const变量不能这样,const变量默认是文件的局部变量。若要改变这种情况则需特别声明
extern const type_Name Variable_Name进行声明。
- * const.cpp
- *
- * Created on: Nov 3, 2011
- * Author: ubuntu
- */
- extern const int a = 78;
- //如果a不声明为extern,则不能在test.cpp中不通过引入文件就访问不到他。
- int b=99;
- #include<iostream>
- //#include"const.cpp"
- using namespace std;
-
- int main()
- {
- extern int b;
- extern const int a;
- cout << a +9<< endl;
- cout << b +89<< endl;
- return 0;
- }
头文件用于声明而不是用于定义。不过有三个例外。头文件可以定义类、值在编译时就已知道的const对象和inline函数。