问题描述
我正在尝试通过一些网络教程来学习C ++.我没有可用的编译器,否则我会尝试一下.我不确定const指针是什么意思.这是否仅表示它始终指向相同的内存地址?你为什么要这么做?以下代码合法吗?
I am trying to learn C++ via some web tutorials. I don't have a compiler available to me, otherwise I would try this out. I'm not sure what is meant by a const pointer. Does that just mean it always points to the same memory address? Why would you ever want to do that? Would the following code be legal?
...
int * const aPointer = new int;
... //do something with aPointer
delete aPointer;
... //do something else, including possibly more 'new' statements
aPointer = new int;
...
推荐答案
记住const如何与指针一起工作的一种简单方法是记住,它始终适用于它左边的任何内容,除非它是最左边的关键字,在这种情况下,它适用于右侧.
A simple way to remember how const works with pointers is to remember that it always applies to whatever is to the left of it, unless it's the left-most keyword, in which case it applies to the right.
示例:
指向常量字符的指针:指针可以更改为指向其他内容,但是它最初指向的char不能更改值.
Pointer to a constant char:The pointer can be changed to point to something else, but the char it initally points to cannot change value.
const char * p;
常量字符:指针不能更改为指向其他任何东西,但是它指向的char可以更改值.
Constant pointer to a char:The pointer cannot be changed to point to anything else, but the char it points to can change value.
char *const p;
常量常量常量指针:指针不能更改为指向其他任何东西,指针所指向的char不能更改值.
Constant pointer to a constant char:The pointer cannot be changed to point to anything else, and the char it points to cannot change value.
const char *const p;
这篇关于C ++的新手.关于常量指针的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!