码迷,mamicode.com
首页 > 编程语言 > 详细

C/C++中的const int*和int * const

时间:2016-04-15 11:43:18      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

代码:

 1 #include <iostream> 
 2 
 3 using namespace std; 
 4 
 5 int main(){
 6     const int *p;
 7     int a = 2;
 8     p = &a;
 9     a = 5;
10     
11     cout<<p<<" "<<*p<<endl;
12 
13     int b = 10;
14     p = &b;
15 
16     cout<<p<<" "<<*p<<endl;
17 
18     //*p = 1; 错误,不允许修改,*p是常量
19     //cout<<*p<<endl;
20     
21     int * const p1 = &a;//此处必须初始化,否则编译错误
22     cout<<p1<<" "<<*p1<<endl;
23 
24     //p1 = &b; 错误,不允许向常量指针赋值
25     //cout<<p1<<" "<<*p1<<endl;
26     
27     const int * const p2 = &a;
28     cout<<p2<<" "<<*p2<<endl;
29     a = 100;
30     cout<<p2<<" "<<*p2<<endl;
31     //*p2 = 290;
32     //p2 = &b; 两者都不允许
33 
34     return 0;
35 }

输出:

0x7ffe6a0ecc34 5
0x7ffe6a0ecc30 10
0x7ffe6a0ecc34 5
0x7ffe6a0ecc34 5
0x7ffe6a0ecc34 100

 

C/C++中的const int*和int * const

标签:

原文地址:http://www.cnblogs.com/hu983/p/5394749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!