C + + reference

A reference variable is an alias, that is, it is another name for an existing variable. Once a reference is initialized to a variable, the reference name or variable name can be used to point to the variable.

C++ references vs Pointers

References are easily confused with Pointers, and there are three major differences:

There is no empty reference. References must be connected to a valid block of memory. Once a reference is initialized to an object, it cannot be pointed to another object. A pointer can point to another object at any time. The reference must be initialized at creation time. Pointers can be initialized at any time.

Create references in C++

Think of a variable name as a label attached to a variable location in memory. You can think of a reference as the second label attached to a variable location in memory. Therefore, you can access the contents of a variable by either the original variable name or a reference. Such as:

int i = 17;

We can declare a reference variable for I, as follows:

int& r = i; double& s = d;

In these declarations, & is read as a reference. Thus, the first declaration can be read as “r is an integer reference initialized to I “, and the second declaration can be read as “s is a double reference initialized to d “. The following example uses int and double references:

#include <iostream> using namespace std; Int main () {// Declare a simple variable int I; double d; // declare the reference variable int &r = I; double& s = d; i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl; D = 11.7; cout << "Value of d : " << d << endl; cout << "Value of d reference : " << s << endl; return 0; }Copy the code

When the above code is compiled and executed, it produces the following results:

Value of I: 5 Value of I reference: 5 Value of D: 11.7 Value of D reference: 11.7Copy the code

References are usually used for function argument lists and function return values. Here are two important concepts that C++ programmers must be aware of in relation to C++ references:

In learning, we often encounter some problems, especially the knowledge don’t understand, my advice is to write down, jump in the past, because the connection between the knowledge of programming is very tight, but also is loose, a question that the road is blocked, we can change train of thought to solve, there is something that the present is not clear, waiting for you to fix up the back of the knowledge, It’s very common to look back and think “that’s the way it is”, so don’t settle for one place.

Finally, when you encounter problems, it is also very important to ask big gods. It is suggested to chat with this group and discuss with seniors. You will also get a lot of help. Can also exchange learning experience, technical problems, you can get PDF books source code, tutorials and so on for free use.