關於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