const在指针中的用法

一、指向const对象的指针---对象不能修改

方式1

int value1 = 3;
const int *p1 = &value1;
*p1 = 5; //错误,不能修改const指向对象的值

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

方式2

const 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;

参考:http://blog.csdn.net/zjf280441589/article/details/23043889

原文地址:https://www.cnblogs.com/zfg-technology/p/4234676.html