1. 程式人生 > 實用技巧 >指標常量與常量指標【C++】

指標常量與常量指標【C++】

常量指標:const int* (int const*)

一個指標,指向的內容是一個常量,內容不能修改,但指標本身可修改。修改內容時,編譯器報錯" error: assignment of read-only location ... "

指標常量: int *const

一個常量,常量本身是一個指標,指標本身不能修改,但指標內容可修改。修改指標時,編譯器報錯"error: assignment of read-only location ..."

如果需要一個指標和指向內容皆為常量,不能更改,可以定義為: const int* const

const int const* 為錯誤語法

 1
#include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int a = 0; 7 int b = 10; 8 int const* p = &a; // 常量指標 9 // 修改指標內容,報錯 10 *p = 5; 11 12 const int* q = &b; // 等價int const* 13 p = q; 14 q = &a; 15 16 int* const w = &a;
17 // 指標常量,報錯 18 w = &b; 19 *w = b; 20 21 const int* const u = w; 22 // 修改地址和內容都報錯 23 u = p; 24 *u = 0; 25 26 return 0; 27 }
View Code