C++中 pointers and const

来源:互联网 发布:软件登记证书 编辑:程序博客网 时间:2024/06/05 16:15

这里写图片描述
图中regular是相对为pointer类型来说,即非pointer类型。
const对指针来说有两种用法:

the first way is to make the pointer point to a constant object, and that prevents you from using the pointer to change the pointed-to-value. The second way is to make the pointer itself constant, and that prevents you from changing where the pointer points.

Three possibilities:

1.Assigns the address of a regular variable to a pointer-to-const

1.1 type of the variable is not pointer

 int age = 39; const int * pt = &age;

It means you cannot use pt to change the value, in other words , the value *pt is const and cannot be modified.

*pt = 20;  //INVALID because pt points to a const int age = 20;  //VALID because age is not declared to be const

It means you cannot use pt to change the value, in other words , the value *pt is const and cannot be modified.
This declaration does not necessarily mean that the value it points to is really a constant; it just means the value is a const insofar as pt is concerned.

1.2[INVALID]type of the variable is pointer

const int n = 12;int *p1;const int **pp2;pp2 = &p1; //NOT ALLOWED

2.Assigning the address of a const variable to a pointer-to-const

const float g_earth = 9.8;const float * pe = &g_earth; // VALID

you can use neither g_earth nor pe to to change the value 9.8 .

3.[INVALID] Assigning the address of a const variable to a regular pointer

const float g_moon = 1.63;float * pm = &g_moon; // INVALID

If you can assign the address of g_moon to pm , then you can cheat and use pm to alter the value of g_moon. That makes a mockery of g_moon’s const status, so C++ prohibits you from assigning the address of a const to a non-const pointer.

0 0