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


          最簡單最清晰的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?


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           

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

          Copyright © iceboundrock

          主站蜘蛛池模板: 绥阳县| 白银市| 临城县| 运城市| 台东市| 扎赉特旗| 琼结县| 永清县| 昌黎县| 巴林左旗| 建平县| 新巴尔虎右旗| 永善县| 仲巴县| 招远市| 文登市| 常熟市| 遵化市| 三门峡市| 庐江县| 奈曼旗| 宁海县| 区。| 沙洋县| 河间市| 三明市| 清镇市| 漠河县| 贡觉县| 武安市| 桦甸市| 三明市| 平和县| 钟山县| 若尔盖县| 靖远县| 昌吉市| 于田县| 岢岚县| 榆社县| 昌江|