1. Const pointer
A pointer variable that points to a constant in the general form of " Const type NAME * pointer variable name. as follows:
int A=12,b=15;const int *p=&a;int *q=&b;*p=22;//Illegal, trying to modify the value of a by P *q=22;//general pointer variable can be modified, legal p=&b;//p instead point to B, legal.
2. References
For data, you can create a "reference" that acts as another alias for the variable.
int main () {int a=5;int &b=a;printf ("%d\n", b);}
The above declares that B is a reference to a, that is, B is an alias of a, so that after the Declaration, the role of A and B is the same, both represent the same variable. This can be understood as: B to refer to a. in the above declaration, "&" is a reference declarator and does not represent an address.
Several points to note:
- A reference is a separate data type. The reference is only declared, not defined. That is, you must first define a variable and then establish a reference to the variable.
- Declares a reference, which must be initialized at the same time, declaring which variable it represents.
- After you declare another variable, you can no longer make it a reference to another variable.
- You cannot create a reference array such as:
int main () {int A[5];int &b[5]=a;//error, cannot establish reference array int &b=a[0];//error, cannot be an alias for array element}
- Referenced references cannot be established.
int main () {int a=3;int &b=a;int &c=b;//establish reference, error}
- You can take a reference to the address, such as declaration B is a reference, then &B is the address of variable A.
int main () {int *pt;pt=&b;//assigns the address of variable a &a to the pointer variable pt}
3. operator new and delete
C + + provides simpler and more powerful operator new and delete instead of malloc and free functions, so it is best not to use malloc and free;
int main () {int m=3,n=4,i;int **a = new int*[m]; Assigns an array of pointers, saves their first address in a , for (i = 0; i < m; i++) //assigns an array to each element of the pointer array a[i] = new int [n];//dynamically declared array, which requires free memory after use. for (i = 0;i < m; ++i) Delete [] a[i];d elete []a;return 0;}
C + + Learning Summary (2)