1. Similarities and differences
Both the reference and the pointer are composite types (compound type), based on the existing type
A reference is a binding to an object, an alias to an object, not a specific object, a pointer to an object, a pointer itself an object
References must be initialized at the time of definition, and only one object cannot be modified; The pointer does not require initialization when it is defined, and the pointer can change the object pointed to
2. Initialization
Initialization of the reference:
1 int 3 2int &ra = A; 3 ++ra; // a=4
View Code
Initialization of the pointer:
1 int 4 ; 2 int *PB = &b;
View Code
The pointer is initialized to NULL:
1 int 0 ; 2 int *p2 = nullstr; 3 int *p3 = NULL; // #include <cstdlib>
View Code
Note: Initialize the pointer with the literal value of 0 , the following two scenarios:
1 int 0 ; 2 Const int 0 ; 3 int *pa = i; // Error 4 int *PB = j; // OK
View Code
3. Reference to reference, pointer to pointer, reference to reference pointer and pointer
referenced reference: Because the reference itself is not a specific object, there is no reference to the reference
1 int 1 ; 2 int &ri = i; 3 int &rii = ri; // OK 4 int& &riii = ri; // Error
View Code
Referring to a reference, first a reference, and then referencing the object is a reference, so parse int& &riii = ri; left side analysis from right to left &rii is a reference, int& the referenced object is a int Types of References
Pointer pointer: The pointer itself is an object, so you can define a pointer to the pointer
1 intx =0;2 int*PX = &x;3 int**pxx = &px;4 5cout << x <<" "<< *px <<" "<< **pxx <<Endl;6cout << &x <<" "<< px <<Endl;7cout << &px <<" "<< pxx << Endl;
View Code
Pointer to reference : As with referenced references, it is clear that pointers to references do not exist
1 int& *p = &ra;
View Code
reference to the pointer :
1 intA =1;2 int*PA = &A;3 int* &rpa =PA;4 5 6cout << PA <<" "<< RPA <<Endl;7cout << *pa <<" "<< *rpa <<Endl;8*rpa =2;9cout << a << Endl;
View Code
Note: For the definition of a more complex variable, the right-to-left analysis method on the left side of the assignment operator is relatively clear
4. About void*
The void* pointer can hold an address of any data type, and other types of pointers can only point to objects of the same type
About pointers and references