C++中麻烦的const(1)

Posted on 2006-11-22 17:03 iceboundrock 阅读(1083) 评论(0)  编辑  收藏 所属分类: 算法与数据结构学习

关于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 


只有注册用户登录后才能发表评论。


网站导航:
 

posts - 10, comments - 15, trackbacks - 0, articles - 0

Copyright © iceboundrock