我们在阅读c++ primer时会经常看到顶层const和底层const,那么到底怎么区分两者?
首先我们来看看译本术语表中对他们的描述:
底层const:一个不属于顶层的const,类型如果由底层常量定义,则不能被忽略。
顶层const:规定对象的值不能改变
文中讲const限定符时有这么几句话:
用名词顶层const表示指针本身是个常量,而用名词底层const表示指针所指的对象是个常量
更一般的,顶层const可以表示任意的对象是常量,这一点对任何数据都适用,如算术类型、类、指针(指针也是个对象)等。底层const则与指针和引用等复合类型的基本类型部分有关,指针既可以是顶层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 the pointer itself is a const. When a pointer can point to a const object, we refer to that const as a low-level const.
所以我们不难看出,当const限定的是对象本身时就是顶层const,若限定的是对象所指的另一个对象时这时就是底层const。