C++ references
A reference variable is an alias, that is, it is another name for an existing variable. Once you initialize a reference to a variable, you can use the reference name or the variable name to point to the variable.
C++ Reference vs Pointer
References are easily confused with pointers. There are three main differences between them:
There is no null reference. The reference must be connected to a valid piece 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.
References must be initialized when created. Pointers can be initialized at any time.
Creating a reference in C++
Imagine that the variable name is the label attached to the memory location of the variable. You can think of the reference as the second label of the memory location attached to the variable. tags. Therefore, you can access the contents of a variable through the original variable name or by reference. For example:
int i = 17;
We can declare a reference variable for i as follows:
int& r = i;
In these declarations, & is read as reference. Therefore, 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 () { // 声明简单的变量 int i; double d; // 声明引用变量 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; }
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.7
References are usually used for function parameter lists and function returns value. Listed below are two important concepts related to C++ references that C++ programmers must know:
Concept | Description |
---|---|
Use references as parameters | C++ supports passing references as parameters to functions, which is safer than passing ordinary parameters. |
References as return values | References can be returned from C++ functions just like other data types. |