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; }}
在可以通過編譯,并且正常運行.但稍加修改后,放在C編譯器中,便會出現錯誤:
#include <stdio.h>int main(){ int i; const int a = 1; const int b = 2; int array[ a + b ] = {0}; for (i = 0; i < sizeof array / sizeof *array; i++) { printf("%d",array[i]); }}
錯誤消息:
c:/test1/te.c(8): error C2057: 應輸入常數表達式c:/test1/te.c(8): error C2466: 不能分配常數大小為 0 的數組
出現這種情況的原因是:
(1)在C中,const是一個不能被改變的普通變量,既然是變量,就要占用存儲空間,所以編譯器不知道編譯時的值.而且,數組定義時的下標必須為常量.
(2)在C語言中:
const int size;
這個語句是正確的,因為它被C編譯器看作一個聲明,指明在別的地方分配存儲空間.但在C++中這樣寫是不正確的.C++中const默認是內部連接,如果想在C++中達到以上的效果,必須要用extern關鍵字.
2.C++中,const默認使用內部連接.而C中使用外部連接.
內連接:編譯器只對正被編譯的文件創建存儲空間,別的文件可以使用相同的表示符
或全局變量.C/C++中內連接使用static關鍵字指定.
外連接:所有被編譯過的文件創建一片單獨存儲空間.一旦空間被創建,連接器必須解決對這片存儲空間的引用.全局變量和函數使用外部連接.通過extern關鍵字聲明,可以從其他文件訪問相應的變量和函數.
header.hconst int test = 1;test1.cpp#include <iostream>#include "header.h"using namespace std;int main(){ cout << "in test1 :" << test << endl;}test2.cpp#include <iostream>#include "header.h"using namespace std;void print(){ cout << "in test2:" << test << endl; }
以上代碼編譯連接完全不會出問題,但如果把header.h改為:
extern const int test = 1;
在連接的時候,便會出現以下錯誤信息:
test2 error LNK2005: "int const test" (?test@@3HB) 已經在 test1.obj 中定義
因為extern關鍵字告訴C++編譯器test會在其他地方引用,所以,C++編譯器就會為test創建存儲空間,不再是簡單的存儲在名字表里面.所以,當兩個文件同時包含header.h的時候,會發生名字上的沖突.
此種情況和C中const含義相似:
header.hconst int test = 1;test1.c#include <stdio.h>#include "header.h"int main(){ printf("in test1:%d/n",test);}test2.c#include <stdio.h>#include "header.h"void print(){ printf("in test2:%d/n",test); }
錯誤消息:
test3 fatal error LNK1169: 找到一個或多個多重定義的符號test3 error LNK2005: _test 已經在 test1.obj 中定義
C++中,是否為const分配空間要看具體情況.
如果加上關鍵字extern或者取const變量地址,則編譯器就要為const分配存儲空間.
C++中定義常量的時候不再采用define,因為define只做簡單的宏替換,并不提供類型檢查