const对象仅在文件内有效

  当以编译时初始化的方式定义一个const对象时,编译器将在编译的过程中把用到该变量的地方都替换成对应的值。为了执行替换,编译器必须知道变量的初始值。如果程序包含多个文件,则每个用了const对象的文件都必须得能访问到它的初始值才行。要做到这一点,就必须在每一个用到变量的文件中都有对它的定义。为了支持这一用法,同时避免对同一变量的重复定义,默认情况下,const对象被设定为仅在文件内有效。当多个文件中出现了同名的const变量时,其实等同于在不同文件中分别定义了独立的变量。

例子:

 

1 // file_1.h
2 #ifndef FILE_1
3 #define FILE_1
4 void f();
5 #endif
1 // func.cpp
2 #include <file_1.h>
3 #include <iostream>
4 
5 const int x = 998;
6 void f()
7 {
8     std::cout << "func:&x " << &x << std::endl;
9 }
 1 // main.cpp
 2 #include <iostream>
 3 #include <string>
 4 #include <file_1.h>
 5 
 6 const int x = 998;
 7 int main()
 8 {
 9     f();
10     std::cout << "main:&x: "<<&x << std::endl;
11     return 0;
12 }

输出:

x的地址完全不一样,说明2个x变量时独立的,不是同一个。

  如果想要在不同的文件间共享同一个const变量怎么办,方法是对于const变量不管是声明还是定义都添加extern关键字,这样只需定义一次就好了。

例子:

1 // file_1.h
2 #ifndef FILE_1
3 #define FILE_1
4 extern const int x;
5 void f();
6 #endif
1 // func.cpp
2 #include <file_1.h>
3 #include <iostream>
4 
5 extern const int x = 998;
6 void f()
7 {
8     std::cout << "func:&x " << &x << std::endl;
9 }
 1 // main.cpp
 2 #include <iostream>
 3 #include <string>
 4 #include <file_1.h>
 5 
 6 extern const int x;
 7 int main()
 8 {
 9     f();
10     std::cout << "main:&x: "<<&x << std::endl;
11     return 0;
12 }

输出:

地址一样,说明是同一个变量

猜你喜欢

转载自www.cnblogs.com/ACGame/p/10053488.html