C++雑談(一)const限定子とconstポインタ

5327 ワード

const限定子
c++には、C言語の#defineの代わりに定数を定義する新しいconstキーワードがあります.const限定子については、以下の点に注意してください.
1.作成後の値は変更されません
2.作用範囲がファイル内で有効
3.externキーワードを追加し、複数のファイルに同じ定数を共有させる
また,int constはconst intと等価である.
 
constポインタ
constポインタを作成すると、const、*と変数タイプの記号の順序が大きく困ります.一般的には、右から左に読むように意味を判断します.
1.
const int *p=&i;

次の文と同等です.
(const int) *p=&i;

const intタイプを指すポインタを表します.
2.
int *const p=&i;

次の文と同等
int *(const p)=&i;

intタイプを指す通常のポインタを表します.このポインタは常にiを指しており,ポインタが指す位置を変えることはできず,指す変数の値を変えることができる.
*p=5;//  

3.
const int *const p=&i;

常変数を指す常ポインタを表し、ポインタの指向を変更したり、ポインタが指す変数の値を変更したりすることはできません.
*p=5;//  

タイプはconst intで、値を変更することはできません.
ここで、左側のconstを最下位const、右側のconstを最上位constと呼びます.
 
constポインタを判断する簡単な方法
*を「pointer to」と読み、右から左へ読む.
bは定数である
const int b;  /* b is a int const */
int const b;  /* b is a const int */

pは通常のポインタであり、定数を指す.
const int *p; /* p is a pointer to int const */
int const *p; /* p is a pointer to const int */

pは定数ポインタであり、通常の変数を指す
int *const p;  /* p is a const pointer to int */

pは定数ポインタであり、定数を指す
const int *const p;  /* p is a const pointer to int const */

int const *const p; /* p is a const pointer to const int */

whchina( ) , , as a thinker。