【转】C++ const用法 尽可能使用const
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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微服务部署:蓝绿部署、滚动部署、灰度发布
- 下一篇: 微信小程序学习:开发注意点