C++ Const pointer declaration(C++ 常量指针声明)
问题描述
我正在查看一些代码,但遇到了一些我不熟悉的代码.经过一番搜索,我想不出任何例子来说明为什么这样做或这个声明的好处.
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 is a
".这意味着你既不能通过这个指针修改指针指向的东西,也不能使指针指向其他地方在它被初始化之后(通过const
pointer to a const
<代码>我的类myClass->getPointer()
).所以是的,你基本上是对的,除了它还指向一个 const
对象(据你所知;它实际上可能是非 const
下面).
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++ 常量指针声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 常量指针声明
基础教程推荐
- 详解c# Emit技术 2023-03-25
- 一文带你了解C++中的字符替换方法 2023-07-20
- C语言 structural body结构体详解用法 2022-12-06
- 如何C++使用模板特化功能 2023-03-05
- C++中的atoi 函数简介 2023-01-05
- C利用语言实现数据结构之队列 2022-11-22
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C/C++编程中const的使用详解 2023-03-26
- C语言基础全局变量与局部变量教程详解 2022-12-31
- C++详细实现完整图书管理功能 2023-04-04