现在的位置: 首页 > 综合 > 正文

学习笔记-const指针,const int * p, int *const p,int const * p的区别

2012年09月11日 ⁄ 综合 ⁄ 共 1998字 ⁄ 字号 评论关闭

 

#include <iostream>
using namespace std;
int main()
{

int Int1 = 1;
int Int2 = 0;
const int* pInt1 = &Int1;
int* const pInt2 = &Int2;
cout<<"*pInt1 = "<<*pInt1<<endl;
cout<<"*pInt2 = "<<*pInt2<<endl;
*pInt1=2;
pInt2=&Int1;
cout<<"*pInt1 = "<<*pInt1<<endl;
cout<<"*pInt2 = "<<*pInt2<<endl;

int n;//为了不让屏幕一闪而消失
cin>>n;
return 0;
}

这样子运行会弹出错误如下

1>------ 已启动生成: 项目: vs2008, 配置: Debug Win32 ------
1>正在编译...
1>main.cpp
1>g:\学习\vs2008project\vs2008\vs2008\main.cpp(12) : error C3892: “pInt1”: 不能给常量赋值
1>g:\学习\vs2008project\vs2008\vs2008\main.cpp(13) : error C3892: “pInt2”: 不能给常量赋值
1>生成日志保存在“file://g:\学习\VS2008Project\vs2008\vs2008\Debug\BuildLog.htm”
1>vs2008 - 2 个错误,0 个警告
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

这里就说明了

pInt1是一个指向整型变量的指针,它所指向的值不能改变,就是 *pInt1这个值不能修改,pInt1所指向的地址可以修改,即pInt1可以修改

pInt2是一个指向整数的常量指针,指针是常量,就是说指针所指向的地址不能改变,就是说pInt2的值不能改变,但是*pInt2可以修改.

可以这样子理解

对于pInt1的定义,const右边是int,所以pInt1所指向的值是常量

对于pInt2的定义,const右边是变量,所以这个变量是常量,而这个变量是什么呢?是看完完整的定义,它是指针,所以这个是指针常量.

下面再看看

int  const * p

#include <iostream>
using namespace std;
int main()
{

int Int1 = 1;
int Int2 = 0;
const int* pInt1 = &Int1;
int* const pInt2 = &Int2;
cout<<"*pInt1 = "<<*pInt1<<endl;
cout<<"*pInt2 = "<<*pInt2<<endl;
*pInt1=2;//第12行
pInt2=&Int1;//第13行
cout<<"*pInt1 = "<<*pInt1<<endl;
cout<<"*pInt2 = "<<*pInt2<<endl;
int const * pInt3 = &Int1;
*pInt3=2;//第17行
pInt3=&Int1;
cout<<"*pInt3 = "<<*pInt3<<endl;
int n;//为了不让屏幕一闪而消失
cin>>n;
return 0;
}
弹出错误如下

1>------ 已启动生成: 项目: vs2008, 配置: Debug Win32 ------
1>正在编译...
1>main.cpp
1>g:\学习\vs2008project\vs2008\vs2008\main.cpp(12) : error C3892: “pInt1”: 不能给常量赋值
1>g:\学习\vs2008project\vs2008\vs2008\main.cpp(13) : error C3892: “pInt2”: 不能给常量赋值
1>g:\学习\vs2008project\vs2008\vs2008\main.cpp(17) : error C3892: “pInt3”: 不能给常量赋值
1>生成日志保存在“file://g:\学习\VS2008Project\vs2008\vs2008\Debug\BuildLog.htm”
1>vs2008 - 3 个错误,0 个警告
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

这样子就说明
int  const * p 和int * const  p是一致的,所以只要看const右边的是什么就可以判断了

int const * p 中const右边是*p 所以p是一个指针常量

int* const  p 中const右边是p,所以这个变量是常量,这个变量是指针,所以这个也是指针常量

const int* p 中const右边是int,所以这个整型是常量,所以说这个*p的值不能改变;

 

thank you

作者: 林羽飞扬
出处:http://www.cnblogs.com/zhengyuhong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留作者信息,且在文章页面明显位置给出原文连接

抱歉!评论已关闭.