c++的指针常量与常量指针

一个指针可以分成两部分来看,那个*为实际存储的内容(*pointer),变量名为那个地址。就是一个指针分成地址和内容两部分。

那么用常量修饰指针,要看修饰的是那个部分,离哪个近就是修饰哪个,哪个就改不了。

两个都修饰的,两个都改不了。

上代码:

	//__________________常量指针__________________
	int HoursInDay=24;
	int const *  pInteger=&HoursInDay;//当用一个const修饰一个指针,那么这个指针将不能用*p修改值
	cout<<"pInteger24:"<<pInteger<<endl;
	cout<<"*pInteger24="<<*pInteger<<endl;

	int MonthsInYear=12;
	pInteger=&MonthsInYear;	
	cout<<"pInteger12="<<pInteger<<endl;
	cout<<"*pInteger12="<<*pInteger<<endl;
	cout<<"HoursInDay="<<HoursInDay<<endl;

	// *pInteger=13;//不可以
	int const * pAnotherPointerToInt=pInteger;//必须完全一样的修饰词才能赋值
	cout<<"pAnotherPointerToInt="<<pAnotherPointerToInt<<endl;
	cout<<"*pAnotherPointerToInt="<<*pAnotherPointerToInt<<endl;

	//_____________________指针常量___________________
	int DaysInMonth=30;
	int * const pDaysInMonth=&DaysInMonth;
	cout<<"pDaysInMonth30="<<pDaysInMonth<<endl;
	* pDaysInMonth=31;//可以
	cout<<"pDaysInMonth31="<<pDaysInMonth<<endl;//地址是不变的

	int DaysInLunarMonth=28;
	//pDaysInMonth=&DaysInLunarMonth;//不可以改变指针地址

	//_____________________双常量指针___________________
	int HoursInDay=24;
	const int * const pHoursInDay=&HoursInDay;
	// * pHoursInDay=25;//不可以
	int DaysInMonth=30;
	// pHoursInDay=&DaysInMonth;//不可以


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值