1. 程式人生 > >四句話解決const賦值問題

四句話解決const賦值問題

  1. 有修飾自己的const就不能再被賦值,且一定要初始化(reference同樣)
  2. 等號右邊修飾自己的const在賦值時會被忽略
  3. 指標的型別有const type(不能用指標修改所指內容)和 type(可以)
  4. 其中 type型別的指標可以賦值給const type型別,因為這樣做相容,反過來就不行。想想也是,從可以修改指向的內容到不能修改所指範圍變窄了。

注:
修飾自己的const 指的是 限定符const
type 指的是 資料型別,如int等
要注意指標的const int是型別!!千萬不要把const int型別跟限定符const搞混,如果你覺得各種const很混亂就是這裡沒理解好!
在《C++ primier》中採用了頂層const和底層const這兩種說法,我覺得這樣更容易弄混,他把const int中的const斷章取義單獨把const拎出來起了個名字叫底層const。至於頂層const就是指限定符const。

這四句話從《c專家程式設計》中總結出來
書中說到賦值的條件:
兩個運算元都是指向有限定符或無限定符的相容型別的指標,左邊指標所指向的型別必須具有右邊指標所指向型別的全部限定符。

自行檢驗我說的對不對,變數命名還是用了top_level_const 和low_level const這種說法(不然真不知道怎麼命名)
帶有lc字樣的是他是const type型別,因此不能修改所指的內容
帶有tc字樣的是帶有限定符const,因此本身不能被修改

 40 void c_r(void){
 41     int i;
 42     const int tc_i = 0; //不能修改tc_i
43 int& r = i; //reference引用 44 const int& lc_r = i; //const int型別的引用 45 int* p; 46 const int* lc_p; //const int* 型別 47 int* const tc_p = &i ;//int* 型別 48 const int* const lc_tc_p = &i ;//int* 型別,帶有限定符const 49 50 i = tc_i;//在賦值時限定符const會被忽略,所以這樣做比較危險,特別是在初始化函式形參的時候會失去限定符const
51 //p = lc_p; //error invalid conversion from 'const int*' to 'int*'不相容 52 lc_p = p; //相容 53 54 //lc_r = r; //error all the assignment of reference is invalid 不能修改帶有限定符const的(或reference) 55 const int& lc_r2 = r;//相容 56 //int& r2 = lc_r; //invalid initialization of reference of type ‘int&’ from expression of type ‘const int’ 型別不相容 57 //so 因此 58 const int& lr_i = 44; //ok,44是const int 59 //int& r_i = 44;//invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’ 60 }

在函式引數傳遞的時候喜歡加const來確保安全性
int a;

void fun1(const int a){}
fun1(a); //從沒有限定符const變為有限定符const,可以,這很安全

void fun2(const int& r){}
fun2(a);//const int型別確保了r不能夠修改a,可以,這很安全

void fun3(const int* lc_p){}
fun3(&a);//const int*型別確保了lc_p不能修改a,可以,這很安全

void fun4(const int* const lc_tp_p){}
fun4(&a);//即不能通過lc_tp_p修改a,又不能用一個新的指標賦值給lc_tp_p,可以,這非常安全