美文网首页
[C++之旅] 5 const的使用

[C++之旅] 5 const的使用

作者: Onicc | 来源:发表于2018-11-24 23:05 被阅读0次

[C++之旅] 5 const的使用

const与基本数据类型

int a = 10;
const int b = 15;

其中a为int类型的变量,b为常量吧,不可修改

const与指针类型

1.
const int *p = NULL;
int const *p = NULL;

上两种表示方法完全等价

int a = 15;
const int *p = &a;

若使用*p = 20;则是错误的;若使用p = &q;(int q = 213;)则是正确的;const限定的是 *p而不是p。

2.
int a = 12;
int *const p = &a;

若使用 p = &q;是错误的,*p = 15;是正确的,即const限定了p所指向的地址,而不限定p所指向地址的内容。

3.
const int *const p = NULL;
int const *const p = NULL;

若使用 p = &q;是错误的,*p = 15;也是错误的,即const限定了p所指向的地址,也限定了p所指向地址的内容。

const 与引用

int a = 45;
const int &b = a;

若使用a = 10;是正确的,使用b = 15;是错误的,即const限定了b,b不能改b的值,但a可以修改。

相关文章

网友评论

      本文标题:[C++之旅] 5 const的使用

      本文链接:https://www.haomeiwen.com/subject/uxduqqtx.html