const char *answer_ptr = "Forty-Two";
does not tell C++ that the variable answer_ptr is a constant. Instead it tells C++ that the data pointed to by answer_ptr is a constant. The data cannot be changed, but the pointer can. Again we need to make sure we know the difference between "things" and "pointers to things."
What's answer_ptr? A pointer. Can it be changed? Yes, it's just a pointer. What does it point to? A const char array. Can the data pointed to by answer_ptr be changed? No, it's constant.
If you put the const after the *, you tell C++ that the pointer is constant. For example:
char *const name_ptr = "Test";
What's name_ptr? A constant pointer. Can it be changed? No. What does it point to? A character. Can the data we pointed to by name_ptr be changed? Yes.
Finally, we put const in both places, creating a pointer that cannot be changed to a data item that cannot be changed:
const char *const title_ptr = "Title";
One way of remembering whether the const modifies the pointer or the value is to remember that *const reads "constant pointer" in English.
博客主要讲解了C++中指针与常量的关系。指出answer_ptr指向的数据是常量不可变,但指针本身可变;若const在*后,指针是常量不可变,指向的数据可变;还提到将const放在两处,指针和指向的数据都不可变,并给出记忆方法。
402

被折叠的 条评论
为什么被折叠?



