C++中麻煩的const(1)
Posted on 2006-11-22 17:03 iceboundrock 閱讀(1112) 評論(0) 編輯 收藏 所屬分類: 算法與數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)關(guān)于const,C++的const是一個非常非常麻煩的關(guān)鍵字,但是如果你不用,也會帶來一些麻煩。
下面一段簡單的程序,演示了const變量,const指針的奇妙關(guān)系
?
?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

?2

?3

?4

?5



?6

?7

?8

?9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

最簡單最清晰的const使用方法就是聲明const變量了,變量需要在生命的地方立即初始化,初始化完成之后就不能再改了。
如果你用同樣的思路來看待const指針,你會發(fā)現(xiàn)你錯的很嚴(yán)重,你看,這個constIntPoint換了幾個目標(biāo)依然生龍活虎,編譯器很愉快的接受了這段代碼,連個warn都沒有。
原來const指針是指向const變量的指針,而不是說指針本身是const的。無
ok,const變量不能直接修改,難道我取到他的地址,再來修改都不行么?不行,編譯器會直接告訴你,無法把一個const的指針轉(zhuǎn)換成普通指針,
Error?1?error C2440: '=' : cannot convert from 'const int *__w64 ' to 'int *'?
論一個變量原來是否被聲明成const,你用一個const指針指向它,然后使用*運(yùn)算符號取出這個變量試圖進(jìn)行修改的操作都是不允許的,參考代碼中被注釋掉的Error2。
Error?2?error C3892: 'constIntPoint' : you cannot assign to a variable that is const?