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

本文标题为:C++ 常量指针声明

基础教程推荐