1、指向const對象的指針---對象不能修改spa
方式1.net
int value1 = 3;
const int *p1 = &value1;
*p1 = 5; //錯誤,不能修改const指向對象的值指針
cout << "value1 = " << value1 << ",*p1 = " << *p1 << endl;對象
方式2blog
const int value1 = 3;
int *p1 = &value1; //錯誤,const int*' to 'int*string
cout << "value1 = " << value1 << ",*p1 = " << *p1 << endl;it
2、 const指針---指針自己值不能修改io
方式1(不能夠修改指針自己)error
int value = 3;
int value2 = 4;
int *const p = &value;
p = &value2; //錯誤,不能修改指針指向的地址,assignment of read-only variable 'p'
cout << "value = " << value << ",*p = " << *p << endl;co
方式2(能夠修改指針指向的值)
int value = 3;
int value2 = 4;
int *const p = &value;
*p = value2; //正確
cout << "value = " << value << ",*p = " << *p << endl; //value = 4,*p = 4
3、指向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;
4、指針和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;
參考:http://blog.csdn.net/zjf280441589/article/details/23043889