The study notes "and" C++ "pointer and the const keyword with examples

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Variables are modified by const means that the variable is a constant, which cannot be modified. And the const keyword and pointer with several need to distinguish together:

Below are several examples of this.

Non const pointer that points to a const object:

const int a;
const int *pa = &a;

Where a is a int type of const object, PA is a pointer to a int type of const object . Need to pay attention to, PA itself is a non const pointer, it can point to other int types of const objects, but the object that it points to is const, which in this case is not through the PA to modify the value of a.

To non const const pointer:

double b;
double *const pb = &b;

Where B is a double type non const objects, Pb is a pointer to the double types of non const object const pointer. Need to pay attention to, Pb itself is const, that is to say that it points to the target can not be changed, this example is B, but B is not const, can change, can also use a PB to modify the value of B.

Pointer to the const object's const pointer:

const int c;
const int *const pc = &c;

Where C is a int type of const object, PC is a pointer to a int const object const pointer. Need to pay attention to, in this example, C and PC is const, which can not be changed, can not change the PC pointing to the object, does not change the object to which PC points c value

To sum up, the statement said in front of the pointer, type const object to point to the const, in the back, pointer variable name in front with const indicates that the pointer itself is const.

In addition, attention should be paid to the pointer types defined by typedef and const when used together, for example:

typedef string *pstring;
const pstring ps;

Here the definition of pstring type to the string object for the pointer of this type, second rows cannot replace in order to understand the simple text:

const string *ps;

Here should understand:

The pstring type is a pointer to a string object, the statement of the PS is a const pstring types, namely PS is a pointer to an object of type string const pointer:

string *const ps;

C++ Primer The study notes

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Matilda at November 16, 2013 - 1:30 PM