1.值替代
c++中const默认为内部链接(internal linkage),cosnt仅在被定义过的文件里才是可见的,而在链接是不能被其他编译单元看到。
在定义const时,必须赋值,除非使用extern进行说明
extern const int bufsize;
通常C++编译器并不为const创建存储空间,相反它把这个定义保存在它的符号表里。但是extern强制进行了存储空间分配(另外,如果取一个const的地址,也要进行存储空间的分配),由于extern意味着使用外部链接,因此必须分配存储空间,这也就是说有几个不同的编译单元应当能够引用他,所以必须有存储空间的分配。
通常,如果定义const对象时,extern不是定义的一部分时,const对象不会分配存储空间,如果使用const,那么编译时,会进行常量折叠(同#define的替换相似)。
参考下面代码(const 对象默认为内部链接)
test.h
#ifndef TEST_H_
#define TEST_H_
const int a = 10;
extern const int b = 15;
int c = 5;//普通变量默认为extern
#endif
test.cpp
#include “test.h”
main.cpp
extern const int a;
extern const int b;
extern int c;
//cout << a << endl;//error C2065: “a”: 未声明的标识符
cout << b << endl;//ok const int
cout << c << endl;//ok
const可以用于聚合,但是编译器不会把聚合保存到它的符号表中,所以必须分配内存。在这种情况下,const意味着“不能改变的一块存储空间”。然而,不能在编译期间使用它的值,因为编译期间不需要知道存储的内容。
extern const int b;
const int carray[] = { 1, 2, 3, 4};
//float f[carray[3]];//error
struct S
{
int i, j;
};
const S s[] = { { 1, 2}, { 3, 4}};
//double d[s[1].j];//error
//double darray [b];//error
编译器为const对象分配空间后,在编译期间不知道const对象的值,因此无法声明数组。