C++-顶层const和底层const是什么 ?

回答如下:

As we’ve seen, a pointer is an object that can point to a different object. As a result,we can talk independently about whether a pointer is const and whether the objectsto which it can point are const. We use the term top-level const to indicate that thepointer itself is a const. When a pointer can point to a const object, we refer tothat const as a low-level const.

正如我们所看到的,指针是一个可以指向不同对象的对象。因此,我们可以独立地讨论一个指针是否为const,以及它所指向的对象是否为const。我们使用术语顶层const表示指针本身是一个const。当一个指针可以指向一个const对象时,我们将该const称为低级的const

简单的说

/** const 规则
 * (1) 从右往左读
 * (2) const 修饰第一个出现在左边的类型
 * (3) 如果左边没有类型,则修饰右边
 */ 
int a = 1;

// 从右往左读,const 修饰的是 int,参见规则(2)
const int * b = &a;
// int const * b = &a; 等价写法,从右往左读,const 修饰的是 int,参见规则(3)

b = new int();	// ok
// *b = 100; 会报错,因为 const 修饰的是指针指向的对象,不能对 *b 赋值
// 根据定义,此时就是底层指针

int * const c = &a; // 从右往左读,const 修饰的是 *,参见规则(2)

*c = 100;	// ok
// c = new int(); 会报错,因为 const 修饰的是指针,不能对 b 赋值
// 根据定义,此时就是顶层指针

另一种对顶层和底层的理解是,指针指向资源对象,可以看作资源对象属于底层指针是资源对外的接口,所以是顶层,对它们常量性的限定,就分别是底层const和顶层const。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值