c++中的const與指標

來源:互聯網
上載者:User

在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既不能修改指向的對象,也不能修改只想對象的值。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.