日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

【转】C++ const用法 尽可能使用const

發(fā)布時(shí)間:2025/4/5 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【转】C++ const用法 尽可能使用const 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

http://www.cnblogs.com/xudong-bupt/p/3509567.html

?

  C++?const 允許指定一個(gè)語義約束,編譯器會(huì)強(qiáng)制實(shí)施這個(gè)約束,允許程序員告訴編譯器某值是保持不變的。如果在編程中確實(shí)有某個(gè)值保持不變,就應(yīng)該明確使用const,這樣可以獲得編譯器的幫助。

1.const 修飾成員變量?

1 #include<iostream>2 using namespace std;3 int main(){4 int a1=3; ///non-const data5 const int a2=a1; ///const data6 7 int * a3 = &a1; ///non-const data,non-const pointer8 const int * a4 = &a1; ///const data,non-const pointer9 int * const a5 = &a1; ///non-const data,const pointer 10 int const * const a6 = &a1; ///const data,const pointer 11 const int * const a7 = &a1; ///const data,const pointer 12 13 return 0; 14 }

const修飾指針變量時(shí):

  (1)只有一個(gè)const,如果const位于*左側(cè),表示指針?biāo)笖?shù)據(jù)是常量,不能通過解引用修改該數(shù)據(jù);指針本身是變量,可以指向其他的內(nèi)存單元。

  (2)只有一個(gè)const,如果const位于*右側(cè),表示指針本身是常量,不能指向其他內(nèi)存地址;指針?biāo)傅臄?shù)據(jù)可以通過解引用修改。

  (3)兩個(gè)const,*左右各一個(gè),表示指針和指針?biāo)笖?shù)據(jù)都不能修改。

2.const修飾函數(shù)參數(shù)

  傳遞過來的參數(shù)在函數(shù)內(nèi)不可以改變,與上面修飾變量時(shí)的性質(zhì)一樣。

void testModifyConst(const int _x) {_x=5;   ///編譯出錯(cuò) }

3.const修飾成員函數(shù)

(1)const修飾的成員函數(shù)不能修改任何的成員變量(mutable修飾的變量除外)

(2)const成員函數(shù)不能調(diào)用非onst成員函數(shù),因?yàn)榉莄onst成員函數(shù)可以會(huì)修改成員變量

1 #include <iostream>2 using namespace std;3 class Point{4 public :5 Point(int _x):x(_x){}6 7 void testConstFunction(int _x) const{8 9 ///錯(cuò)誤,在const成員函數(shù)中,不能修改任何類成員變量 10 x=_x; 11 12 ///錯(cuò)誤,const成員函數(shù)不能調(diào)用非onst成員函數(shù),因?yàn)榉莄onst成員函數(shù)可以會(huì)修改成員變量 13 modify_x(_x); 14 } 15 16 void modify_x(int _x){ 17 x=_x; 18 } 19 20 int x; 21 };

?4.const修飾函數(shù)返回值

(1)指針傳遞

如果返回const data,non-const pointer,返回值也必須賦給const data,non-const pointer。因?yàn)橹羔樦赶虻臄?shù)據(jù)是常量不能修改。

1 const int * mallocA(){ ///const data,non-const pointer2 int *a=new int(2);3 return a;4 }5 6 int main()7 {8 const int *a = mallocA();9 ///int *b = mallocA(); ///編譯錯(cuò)誤 10 return 0; 11 }

(2)值傳遞

?如果函數(shù)返回值采用“值傳遞方式”,由于函數(shù)會(huì)把返回值復(fù)制到外部臨時(shí)的存儲(chǔ)單元中,加const 修飾沒有任何價(jià)值。所以,對于值傳遞來說,加const沒有太多意義。

所以:

  不要把函數(shù)int GetInt(void) 寫成const int GetInt(void)。
  不要把函數(shù)A GetA(void) 寫成const A GetA(void),其中A 為用戶自定義的數(shù)據(jù)類型。

?

  在編程中要盡可能多的使用const,這樣可以獲得編譯器的幫助,以便寫出健壯性的代碼。

轉(zhuǎn)載于:https://www.cnblogs.com/mimime/p/7678404.html

總結(jié)

以上是生活随笔為你收集整理的【转】C++ const用法 尽可能使用const的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。