C++ 常量指針與指針常量

        1、常量指針(constant pointers):指針自身是常量,const關鍵字出如今星號右邊。如:spa

1 char greeting[] = "Hello";
2 char* const p = greeting; // const pointer, non-const data

        2、指針常量(pointers to constants):指針所指物是常量,const關鍵字出如今星號左邊。如: 指針

1 char greeting[] = "Hello"; 2 const char* p = greeting;      // non-const pointer, const data


        我對這兩個概念的理解來自於《Effective C++》(第三版,侯捷譯)。code

        在該書的第一章-條款02中有這樣一段話:」當咱們以常量替換#defines, 有兩種特殊狀況值得說說。第一是定義常量指針(constant pointers)。因爲常量定義式一般被放在頭文件內......所以有必要將指針(而不僅是指針所指之物)聲明爲const。「。由此獲得常量指針的定義。blog

        結合第二章-條款03中的這段話:「若是關鍵字const出如今星號左邊,表示被指物是常量;若是出如今星號右邊,表示指針自身是常量;......」,就獲得了C++中常量指針與指針常量的定義與區別。class

相關文章
相關標籤/搜索