const的修饰规则

const在*的左边,则指针指向的变量的值不可直接通过指针改变(可以通过其他途径改变);

const在*的右边,则指针的指向不可变。简记为“左定值,右定向”。

(1)指针可以改变,指向的值不能改变

    int a=10;
    const int *p1=&a;    //例如:允许 p1+=1 ,不允许 *p1=20
    int const *p2=&a;    //这两句效果一样

(2)指向的值可以改变,指针不可改变

    int a=1;

    int b=2;

    int *const p3=&a;     //例如:允许 *p=3 ,不允许 p3=&b

(3)指针和指向的值都不能改变

    int a=10;
    const int * const p4=&a;

    int const* const p4=&a;      //这两种写法一样

 

=====================================更新=====================================

const int *p1 可看作是const修饰的类型是int,修饰的内容是*p1,即*p1不允许改变。

int const *p2 可以看作const修饰的类型是int,修饰的内容是*p2,即*p2不允许改变。

int *const p3 可以看作const修饰的类型是int *,修饰的内容是p3,即p3不允许改变。

const修饰的类型是根据离const最近的类型来决定的。

修饰符*和&应当紧靠变量名,所以应当首先找离修饰符最近的变量名做匹配,而不是const。】

==============================================================================

 

const只有在修饰的内容里面存在*才参与数据类型。

//?猜测: const修饰的类型里面带的*号可以删去,因此下面的例子中重载类型第一个和第三个可看作是同一种类型。
 

#include<iostream>
using namespace std;
/*
int fun(int *a,int *b)
{
	cout<<typeid(a).name()<<"   "<<typeid(b).name()<<endl;
	cout<<"int fun(int *a,int* b)"<<endl;
	return 0;
}*/
int fun(const int *a,const int* b)
{
	cout<<typeid(a).name()<<"   "<<typeid(b).name()<<endl;
	cout<<"int fun(const int *a,const int* b)"<<endl;
	return 0;
}
int fun(int *const a,int *const b)
{
	cout<<typeid(a).name()<<"    "<<typeid(b).name()<<endl;
	cout<<"int fun(int *const a,int *const b)"<<endl;
	return 0;
}

int main()
{
	int a = 10;
	int *p = &a;

	const int b = 20;
	const int *p2 = &b;

	//const只有在修饰的内容里面存在*才参与数据类型
	//?猜测: const修饰的类型里面带的*号可以删去,因此重载类型第一个和第三个可看作是同一种类型。
	fun(p,p);
	fun(p2,p2);

	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值