【轉】C++ const用法 儘可能使用const

來源:互聯網
上載者:User

標籤:分享   代碼   .com   font   mutable   有一個   title   返回   space   

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

 

  C++ const 允許指定一個語義約束,編譯器會強制實施這個約束,允許程式員告訴編譯器某值是保持不變的。如果在編程中確實有某個值保持不變,就應該明確使用const,這樣可以獲得編譯器的協助。

1.const 修飾成員變數 

 1 #include<iostream> 2 using namespace std; 3 int main(){ 4     int a1=3;   ///non-const data 5     const int a2=a1;    ///const data 6  7     int * a3 = &a1;   ///non-const data,non-const pointer 8     const int * a4 = &a1;   ///const data,non-const pointer 9     int * const a5 = &a1;   ///non-const data,const pointer10     int const * const a6 = &a1;   ///const data,const pointer11     const int * const a7 = &a1;   ///const data,const pointer12 13     return 0;14 }

const修飾指標變數時:

  (1)只有一個const,如果const位於*左側,表示指標所指資料是常量,不能通過解引用修改該資料;指標本身是變數,可以指向其他的記憶體單元。

  (2)只有一個const,如果const位於*右側,表示指標本身是常量,不能指向其他記憶體位址;指標所指的資料可以通過解引用修改。

  (3)兩個const,*左右各一個,表示指標和指標所指資料都不能修改。

2.const修飾函數參數

  傳遞過來的參數在函數內不可以改變,與上面修飾變數時的性質一樣。

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

3.const修飾成員函數

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

(2)const成員函數不能調用非onst成員函數,因為非const成員函數可以會修改成員變數

 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         ///錯誤,在const成員函數中,不能修改任何類成員變數10         x=_x;11 12         ///錯誤,const成員函數不能調用非onst成員函數,因為非const成員函數可以會修改成員變數13         modify_x(_x);14     }15 16     void modify_x(int _x){17         x=_x;18     }19 20     int x;21 };

 4.const修飾函數傳回值

(1)指標傳遞

如果返回const data,non-const pointer,傳回值也必須賦給const data,non-const pointer。因為指標指向的資料是常量不能修改。

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

(2)值傳遞

 如果函數傳回值採用“值傳遞方式”,由於函數會把傳回值複製到外部臨時的儲存單元中,加const 修飾沒有任何價值。所以,對於值傳遞來說,加const沒有太多意義。

所以:

  不要把函數int GetInt(void) 寫成const int GetInt(void)。
  不要把函數A GetA(void) 寫成const A GetA(void),其中A 為使用者自訂的資料類型。

 

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

【轉】C++ const用法 儘可能使用const

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.