C++中麻煩的const(1)

來源:互聯網
上載者:User

關於const,C++的const是一個非常非常麻煩的關鍵字,但是如果你不用,也會帶來一些麻煩。

下面一段簡單的程式,示範了const變數,const指標的奇妙關係

 

 

 1  #include  " stdafx.h " 
 2  
 3  
 4  int  _tmain( int  argc, _TCHAR *  argv[])
 5    {
 6   const   int  constInt1  =   1 ;
 7  
 8   const   int   * constIntPoint  =  NULL;
 9  
10   int   * IntPoint  =  NULL;
11  
12  constIntPoint  =   & constInt1;
13  
14   const   int  constInt2  =   2 ;
15  
16   int  Int3  =   3 ;
17  
18   // IntPoint = &constInt2;  // Error 1 
19  
20  
21  constIntPoint  =   & Int3;
22  
23   // (*constIntPoint)++;  // Error 2 
24  
25  printf( " constInt1=%d\r\n " , constInt1);
26  printf( " constInt2=%d\r\n " , constInt2);
27  printf( " Int3=%d\r\n " , Int3);
28  
29  printf( " constIntPoint point to %d\r\n " ,  * constIntPoint);
30   return   0 ;
31 } 
32  
33  

最簡單最清晰的const使用方法就是聲明const變數了,變數需要在生命的地方立即初始化,初始化完成之後就不能再改了。

如果你用同樣的思路來看待const指標,你會發現你錯的很嚴重,你看,這個constIntPoint換了幾個目標依然生龍活虎,編譯器很愉快的接受了這段代碼,連個warn都沒有。
原來const指標是指向const變數的指標,而不是說指標本身是const的。無

ok,const變數不能直接修改,難道我取到他的地址,再來修改都不行嗎?不行,編譯器會直接告訴你,無法把一個const的指標轉換成普通指標,

Error 1 error C2440: '=' : cannot convert from 'const int *__w64 ' to 'int *' 

論一個變數原來是否被聲明成const,你用一個const指標指向它,然後使用*運算子號取出這個變數試圖進行修改的操作都是不允許的,參考代碼中被注釋掉的Error2。

Error 2 error C3892: 'constIntPoint' : you cannot assign to a variable that is const 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.