const在指標中的用法

2022-07-16 17:33:16 字數 1812 閱讀 2915

一、指向const物件的指標---物件不能修改

方式1int value1 = 3;

const int *p1 = &value1;

*p1 = 5; //錯誤,不能修改const指向物件的值

cout << "value1 = " << value1 << ",*p1 = " << *p1 << endl;

方式2const int value1 = 3;

int *p1 = &value1; //錯誤,const int*' to 'int*

cout << "value1 = " << value1 << ",*p1 = " << *p1 << endl;

二、const指標---指標本身值不能修改

方式1(不可以修改指標本身)

int value = 3;

int value2 = 4;

int *const p = &value;

p = &value2; //錯誤,不能修改指標指向的位址,assignment of read-only variable 'p'

cout << "value = " << value << ",*p = " << *p << endl;

方式2(可以修改指標指向的值)

int value = 3;

int value2 = 4;

int *const p = &value;

*p = value2; //正確

cout << "value = " << value << ",*p = " << *p << endl;  //value = 4,*p = 4

三、指向const物件的const指標---既不能修改指標的值,也不能修改指標所指向物件的值

const int value = 3;(或者 int value = 3)

const int *const p = &value;

int value2 = 4;

p = &value2; //不能修改指標本身,error: assignment of read-only variable 'p'

*p = 5;   //不能修改指標指向的值, error: assignment of read-only location '*(const int*)p'

cout << "value = " << value << ",*p = " << *p << endl;

四、指標和typedef

方式1(錯誤原因?)

typedef string *pstring;

const pstring p; //錯誤,沒有初始化,error: uninitialized const 'p'

方式2(正確)

typedef string *pstring;

const string p; //正確,string型別定義可以不初始化

在c++中,const限定符既可以放在型別前面也可以放在型別後,即下面兩條語句的作用是完全相同的

const string s == string const s;

/**示例,下面的幾條定義的作用是一樣的!

*/string s;

typedef string *pstring;

const pstring p1 = &s;

pstring const p2 = &s;

const string *p3 = &s;

string const *p4 = &s;

參考:

const在c中的用法

常量和變數的樣子完全一樣,只是常量的值不允許被修改。我們用const這個關鍵字來宣告乙個常量。例 const int a 10 int const a 10 兩種方式都可以宣告乙個常量效果是一樣的。我們也可以用const來修飾指標 const與識別符號 例 define num 20 const i...

c 指標中const的用法總結

include using namespace std int main int b1 1,b2 2,b3 3,b4 4,b5 5 int c 100 const int cc 1000 int p const int a1 b1 const修飾a指向的物件b,a可變,a指向的物件b不可變 int ...

C 中const和指標的用法

名稱是根據const和指標順序的。實際作用是根據const修飾的型別,修飾型別的資料不能改變。按照上面的兩條原則,常量指標應該是const int p這樣的寫法,作用是 如下 int a 20 int b 30 常量指標 int 指標指向的值不能改變 指標的指向可以改變 const int p a ...