c++ references and pointers

Reference:
Write the declarator in the form of &d to define a reference type, where d is the variable name.
1. A reference is not an object, it is just an alias for an existing object.
2. The reference must be initialized. Once the initialization is completed, the reference will always be bound to its initial value.
3. A reference can only be bound to an object, not to a literal value or the evaluation result of an expression.
4. Normally, the type of the reference should strictly match the object bound to it.
Exception:
Constant references:
double x = 1.2;
const int &p = x;
Initializing a reference to a constant is allowed to use an arbitrary expression as an initial value, as long as the result of the expression can be converted to the type of the reference.


Pointer:
Write the declarator in the form of *d to define a reference type, where d is the variable name.
1. A pointer is an object and does not need to be assigned an initial value when it is defined; if a pointer defined in the block-level scope is not initialized, it will also have an indeterminate value.
2. Under normal circumstances, the type of the pointer must strictly match the object it points to.
Exception:
pointer to constant: cannot be used to change the value of the object to which it points.
int x = 1.2;
const int *p = &x;
allows a pointer to a const to point to a non-const object.
3. If the pointer points to an object, it is allowed to use the dereference character (*) to access the object;
dereferencing the pointer will obtain the pointed object, so if you assign a value to the dereferenced result, you will assign the pointed object Assignment.


Const pointer:
that is, a constant pointer, which must be initialized, and once the initialization is completed, its value (that is, the address stored in the pointer) cannot be changed.
Put * before the const keyword to indicate that the pointer is a constant.
int x = 1;
int * const p = &x; // p will always point to x

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325223151&siteId=291194637