const和*,**搭配的解释

1 篇文章 0 订阅
1 篇文章 0 订阅

const和*,**搭配的解释

注:以下举例以int作为类型,且new的数据未作delete处理

类型一:const 和 int

//类型一
	const int i1 = 2;//【Ⅰ】
	// i1 = 3;//error

	int const i2 = 2;//【Ⅱ】等价于【Ⅰ】
	//i2 = 3;//error 

类型二:const和 int 和 *

    int* tpi = new  int(1);
	int** tppi = new int* (new int(1));
	
	//类型二
	const int* pi_11{ new int(2) };//【Ⅲ】pi_11指向的值为常量
	//(*pi_11) = 3;//error
	pi_11 = tpi;//success

	int const* pi_12{ new int(2) };//【Ⅳ】等价于【Ⅲ】
	//(*pi_12) = 3;//error
	pi_12 = tpi;//success
	*tpi = 3;
	int* const pi_13{ new int(2) };//Ⅴ】pi_13指针为常量
	(*pi_13) = 3;//success
	//pi_13 = tpi;//error

	const int* const pi{ new int(2) };//【Ⅵ】pi指针为常量,且pi指向的值也为常量
	//pi = tpi;//error
	//(*pi) = 3;//error

类型三:const 和 int 和 **

    int* tpi = new  int(1);
	int** tppi = new int* (new int(1));
    const int* pi_11{ new int(2) };
	//类型三
	int* const* const ppi1{ new int* (new int(2)) };//【Ⅶ】ppi1指针为常量,且ppi1指针的指针为常量
	//ppi1 = tppi;//error
	//(*ppi1) = tpi;//error
	(*(*ppi1)) = 3;//success

	const int* const* const ppi2{ new int* (new int(2)) };//【Ⅷ】ppi2指针为常量,且ppi2指针的指针为常量,且ppi2指针的指针指向的值也为常量
	//ppi2 = tppi;//error
	//(*ppi2) = tpi;//error
	//(*(*ppi2)) = 3;//error
	int const * const* const ppi3{ new int* (new int(2)) };//【Ⅸ】等价于【Ⅷ】

	int** const ppi4{ new int* (new int(2)) };//【Ⅹ】ppi5二级指针为常量
	//ppi4 = tppi;//error
	(*ppi4) = tpi;//success
	(*(*ppi4)) = 2;//sucess

	const int** ppi5{ new const int* (new int(2)) };//【ⅩⅠ】ppi5指针的指针指向的值为常量
	ppi5 = &pi_11;//success
	(*ppi5) = pi_11;//success
	//(*(*ppi5)) = 2;//error

	int const** ppi6{ new const int* (new int(2)) };//【ⅩⅡ】等价于【ⅩⅠ】

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值