设为首页 加入收藏

TOP

Duanxx的C++学习: const指针详解
2015-07-20 17:28:56 来源: 作者: 【 】 浏览:3
Tags:Duanxx 学习 const 指针 详解

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

关键字const使得代码可以确定一个变量是否可以被修改。

使用了const后,可以防止对变量或者指针的修改;更重要的是,const的引用可以防止对所引用的对象的修改。

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

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

关于Const的指针的使用,文字解说没有意义,直接参见下面的代码及注释:

#include 
  
   
// 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; ///
   
    

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Phalcon 之命令行应用(Command L.. 下一篇C++调用约定和名字约定

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Python爬虫教程(从 (2025-12-26 16:49:14)
·【全269集】B站最详 (2025-12-26 16:49:11)
·Python爬虫详解:原 (2025-12-26 16:49:09)
·Spring Boot Java: (2025-12-26 16:20:19)
·Spring BootでHello (2025-12-26 16:20:15)