问题描述
我正在查看一些代码,我遇到了一些我不熟悉的代码。经过一番搜索,我找不到任何为什么这样做或这个声明的好处的例子。
I am reviewing some code and I ran across some code I am unfamiliar with. After some searching I could not come up of any example of why this is done or the benefit of this declaration.
myClass const * const myPtr = myClass->getPointer();
这是一个const指针或完全不同的声明吗?
Is this a declaration of a const pointer or something entirely different?
推荐答案
这意味着 myPtr
是 const
指向 const
myClass
。这意味着您不能通过此指针修改指针所指向的 ,也不能在初始化之后将指针指向其他位置(由返回值 myClass-> getPointer()
)。所以是的,你基本上是对的,除了它还指向一个 const
对象(就你所知;它可以真正是非 - <$ c $
It means "myPtr
is a const
pointer to a const
myClass
". It means that you can neither modify what the pointer is pointing at through this pointer nor can you make the pointer point somewhere else after it's initialised (by the return value of myClass->getPointer()
). So yes, you're basically right, with the addition that it also points to a const
object (as far as you know; it could really be non-const
underneath).
请记住, const
适用于左(或如果没有项目在其左边,项目在它的右边)。第一个 const
使 myClass
const
不修改指针指向的位置),第二个 const
使得 *
const指针本身)。
Remember that const
applies to the item to its left (or if there is no item to its left, the item to its right). The first const
makes the myClass
const
(where you can't modify what the pointer points at) and the second const
makes the *
const (where you can't modify the pointer itself).
这篇关于C ++ const指针声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!