首页 > 编程语言 > 详细

Duanxx的C++学习: const指针具体解释

时间:2014-10-18 16:38:46      阅读:200      评论:0      收藏:0      [点我收藏+]

 Const指的是一个编译时的常量。

         keywordconst使得代码能够确定一个变量能否够被改动。

使用了const后,能够防止对变量或者指针的改动;更重要的是,const的引用能够防止对所引用的对象的改动

 

一般来说,在C语言中,对于一些常量的定义,我习惯性的使用define,而在C++中则最好改为使用const。

 

对于嵌入式程序而言,const的使用则是相当的微妙的,被const修饰后,其变量是存放在ROM中的,这一点非常重要。

 

关于Const的指针的使用,文字讲解没有意义,直接參见以下的代码及凝视:

#include <iostream>
// const
// - a compile time constraint that an object can not be modified

int main()
{
	const int i = 1;
	int a = 0;
	const int *p1 = &i;		///< data is const ,but pointer is not

	int* const p2 = &a;	    ///< pointer p2 itself is const ,but the data p2 point to is not const
	//int* const p3 = &i;     ///< illegal , cannot convert from 'const int *' to 'int *const '
	int const* p4 = p1;      ///< if const is on the left of *,data is const
						///< if cosnt is on the right of *,pointer is const

	const int* const p5 = &i; ///<the data and the pointer are both const

	return 0;
}


Duanxx的C++学习: const指针具体解释

原文:http://www.cnblogs.com/hrhguanli/p/4033215.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!