太久不用 C++ 了,竟然连最基本的东西都记不清楚了。今天干活的时候突然想要用指针常量,但突然就忘了指针常量跟常量指针的区别。花了一点儿时间仔细回想了一下几年前上课时老师讲的,总算又回忆起来了,赶紧记录下来备忘。
这可能会被当作面试题,不过不是算法,故而不放在面试算法题系列中。
我觉得容易混淆的罪魁祸首在于中文的翻译问题,如果改叫「常量的指针」和「指针常量」可能会好些。先不管这些,看看英文的叫法:Pointer to Const 和 Const Pointer。
Pointer to Const,顾名思义就是一个指针,指向的数据不能被修改,C++ 语法是 intconst*ptr。怎么记忆呢,非常简单,记住要从右往左解读即可。首先这是个变量(ptr);然后发现它是个指针(*);接下来看到它所指向的数据是不可修改的(const);最后这个指针所指向的空间存放的是整数(int)。
inta1=1;intb1=2;intc1=3;int*pointer=&a1;intconst*pointerToConst=&b1;int*constconstPointer=&c1;inta2=10;intb2=20;intc2=30;pointer=&a2;pointerToConst=&b2;//constPointer = &c2; // the pointer cannot be moved
*pointer+=100;//*pointerToConst += 100; // the pointed data cannot be changed
*constPointer+=100;cout<<"*pointer = "<<*pointer<<"\n"<<"*pointerToConst = "<<*pointerToConst<<"\n"<<"*constPointer = "<<*constPointer<<endl;
inta=0;intb=1;// An int that cannot be changed.
constintconstNumber_1=a;intconstconstNumber_2=a;//constNumber_1 = 10;
// A pointer that can be repointed to an int that cannot be changed.
constint*pointerToConst_1=&a;intconst*pointerToConst_2=&a;pointerToConst_1=&b;//*pointerToConst_1 = 10;
// A pointer that cannot be moved to an integer that may be changed.
int*constconstPointer=&a;//constPointer = &b;
*constPointer=10;// A pointer that cannot be moved to an integer that cannot be changed.
constint*constconstPointerToConst_1=&a;intconst*constconstPointerToConst_2=&a;//constPointerToConst_1 = &b;
//*constPointerToConst_1 = 10;
// Error, const applied to int twice.
// (warning C4114: same type qualifier used more than once).
constintconst*pointerToTwiceConst=&a;pointerToTwiceConst=&b;//*pointerToTwiceConst = 10;
// A pointer that may be repointed. It points to a pointer that cannot be moved to
// an int that may be modified.
int*pa=&a;int*const*pointerToConstPointer=&pa;int*pb=&b;pointerToConstPointer=&pb;//*pointerToConstPointer = pb;
**pointerToConstPointer=10;
评论需要 JavaScript。