日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

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

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

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

?

  C++?const 允許指定一個語義約束,編譯器會強(qiáng)制實施這個約束,允許程序員告訴編譯器某值是保持不變的。如果在編程中確實有某個值保持不變,就應(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修飾指針變量時:

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

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

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

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

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

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

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

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

(2)const成員函數(shù)不能調(diào)用非onst成員函數(shù),因為非const成員函數(shù)可以會修改成員變量

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成員函數(shù)中,不能修改任何類成員變量 10 x=_x; 11 12 ///錯誤,const成員函數(shù)不能調(diào)用非onst成員函數(shù),因為非const成員函數(shù)可以會修改成員變量 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。因為指針指向的數(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(); ///編譯錯誤 10 return 0; 11 }

(2)值傳遞

?如果函數(shù)返回值采用“值傳遞方式”,由于函數(shù)會把返回值復(fù)制到外部臨時的存儲單元中,加const 修飾沒有任何價值。所以,對于值傳遞來說,加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)容還不錯,歡迎將生活随笔推薦給好友。