C++基礎概念:const關鍵字

1) 定義常量

有時候我們希望定義這樣一種變數, 它的值不能被改變。

為了滿足這一 要求, 可以用關鍵字 const 對變數的型別加以限定。

const物件一旦建立後其值就不能再改變,所以const物件

必須在定義的時候就初始化。

初始值可以是任意複雜的表示式。

與非const型別所能參與的操作相比,const 型別的物件能完成其中大部分;

主要的限制就是

只能在 const 型別的物件上執行不改變其內容的操作

// const int max ; //error: uninitialized const ‘max’ const int max = 100 ; cout << max << endl ; int j = max ; cout << j << endl ;// max = j ; //error: assignment of read-only variable ‘max’

const定義常量與define的區別:

const是有型別的,可以做型別檢查;define只是替換,是沒有型別檢查的,容易出錯。

所以在C++推薦的做法是使用const,不推薦使用define

2) 定義常量指標

const T *用於定義常量指標。

不可透過常量指標修改其指向的內容

int n = 4 ; const int *p = &n ;// *p = 5 ; // error: assignment of read-only location ‘* p’

常量指標指向的位置可以變化

int n = 4 ; const int *p = &n ; n =5 ; int m = 6 ; p = &m ; cout << *p << endl ;

不能把常量指標賦值給非常量指標,反過來可以

int n = 4 ; const int *p = &n ; n =5 ; int m = 6 ; p = &m ; int * p2 = &n ; p = p2 ; // no error cout << *p << endl ;// p2 = p ; //error: invalid conversion from ‘const int*’ to ‘int*’

3) 定義常引用

不能透過常引用修改其引用的變數

const int &r = m ; cout << r << endl ;// r = n ; //error: assignment of read-only reference ‘r’

const T 型別的常變數和 const T & 型別的引用則不能用來初始化 T & 型別的引用

T &型別的引用 或 T型別的變數可以用來初始化 const T & 型別的引用。

int & r = m ; const int &t = r ;// int & y = t ; // error: binding reference of type ‘int&’ to ‘const int’ discards qualifiers

參考程式碼:

#include #include using namespace std;int main (){// const int max ; //error: uninitialized const ‘max’ const int max = 100 ; cout << max << endl ; int j = max ; cout << j << endl ;// max = j ; //error: assignment of read-only variable ‘max’ int n = 4 ; const int *p = &n ;// *p = 5 ; // error: assignment of read-only location ‘* p’ cout << *p << endl ; n =5 ; cout << *p << endl ; int m = 6 ; p = &m ; cout << *p << endl ; int * p2 = &n ; p = p2 ; cout << *p << endl ;// p2 = p ; //error: invalid conversion from ‘const int*’ to ‘int*’ int & r = m ; const int &t = r ; cout << t << endl ;// t = n ; //error: assignment of read-only reference ‘t’// int & y = t ; // error: binding reference of type ‘int&’ to ‘const int’ discards qualifiers return 0 ;}

輸出結果:

g++ const_pointer。cpp。/a。out10010045656