const对象默认为文件的局部变量,与其他变量不同,除非特别说明,在全局作用域的const变量时定义该对象的文件局部变量。此变量只存在于那个文件中中,不能别其他文件访问。要是const变量能在其他文件中访问,必须显示的指定extern(c中也是)
当你只在定义该const常量的文件中使用该常量时,c++不给你的const常量分配空间--这也是c++的一种优化措施,没有必要浪费内存空间来存储一个常量,此时const int c = 0;相当于#define c 0;
当在当前文件之外使用时,c++会给你的const分配空间(它是迫不得已)。因为若此时如果不分配空间,则obj中根本就不会有该常量的信息。连接的时候就找不到该常量。同样如果你在程序中取了常量的地址,也回迫使c++给你的常量分配空间。
C++编译器在通常情况下不为常量分配空间,而是将其值存放在符号表内.但当使用extern修饰常量时,则必须立即为此常量分配空间(与之类似的情况还有取常量的地址等等).只所以必须分配空间,是因为extern表示"使用外部链接",这表明还会有其他的编译单元将会使用寻址的方法来引用它,因此它现在就必须拥有自己的地址.
所以如果想在当前文件使用其他文件的const变量时,这个变量就必须定义成:(m.cpp) extern const int aaa = 9999;使用时需要:(main.cpp) extern const int aaa;在c中就不必再定义是加extern,因为始终为const变量分配空间。
const的形参重载:
#include <iostream>
using namespace std;
void f(int& a)
{
cout << "void f(int& a)" << endl;
}
void f(const int& a)
{
cout << "void f(const int& a)" << endl;
}
int main()
{
int a = 6;
int &b = a;
const int c = 8;
f(a);
f(b);
f(c);
f(3);
return 0;
}
运行结果:
void f(int& a)
void f(int& a)
void f(const int& a)
void f(const int& a)
C与C++中const的区别
1.C++中的const正常情况下是看成编译期的常量,编译器并不为const分配空间,只是在编译的时候将期值保存在名字表中,并在适当的时候折合在代码中.所以,以下代码:
#include <iostream>
using namespace std;
int main()
{
const int a = 1;
const int b = 2;
int array[ a + b ] = {0};
for (int i = 0; i < sizeof array / sizeof *array; i++)
{
cout << array[i] << endl;
}
}










