C++ 常量指针声明

C++ Const pointer declaration(C++ 常量指针声明)
本文介绍了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++ 常量指针声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)