在c/c++中,指標本身就是一個痛點,再加與const的結合,常會產生許多讓人費解的地方,在這裡做個小結。
1.定義const對象
const int buffsize=512;
因為常量定義後就不能修改,所以定義時必須初始化.
const i,j=0; //error,i沒有初始化
2.const對象預設為檔案的局部變數
//file1.cc
extern const int bufsize=512; //定義並初始化
//file2.cc
extern const int bufsize; //聲明
for(int index=0;index!=bufsize;++index)
{
//...
}
非const變數預設為extern,要使const變數能夠在其它的檔案中訪問,必有顯示指定為extern.
3.指向const對象的指標
const int *p;
這個p是一個指向int類型const對象的指標,const限定了指標p所指向的類型,而並非p本身。也就是說p
本身並不是const。在定義時不需要對它進行初始化,還可以給p重新賦值,使其指向另一個const對象。
但不能通過p修改所指向對象的值。
樣本1:int a=0; p=&a; 可以。
樣本2:*p=20; 不可以。
結論:這種指向const對象的指標只是限制不能修改p指向對象的數值,而不是限制p指向什麼對象。
把一個const對象的地址賦給一個不是指向const對象的指標也是不行的。
樣本3:const int b=10;
int *p2=&b; //error
const int *p3=&b; //ok
結論:因為變數b有const修飾,不能被修改。但指標p2是一個普通的指標,可以修改指向對象的值,兩種
聲明矛盾,所以不合法。而指向const對象的指標不允許修改指標指向對象的數值,所以這種方式合法。
不能使用void*指標儲存const對象的地址,而必須使用const void*類型儲存const對象的地址。
const int a=6;
void *p=&a;//error
const *cp=&a;//ok
int const *p;
c++規定,const關鍵字放在類型或變數名之前是等價的.
const int n=5; //same as below
int const m=10;
const int *p; //same as below const (int) * p
int const *q; // (int) const *p
4.const指標
int c=20;
int *const p4=&c;
指標p4稱為const指標。它和指向const對象的指標恰好相反,它不能夠修改所指向對象,但卻能夠修改指
向對象的數值。另外,這種指標在聲明時必須初始化。
5.指向const對象的const指標
const int d=30;
const int *const dp=&d;
指標dp既不能修改指向的對象,也不能修改只想對象的值。