const在指针中的用法

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

相关文章
相关标签/搜索