May 11, 2021 C++
A reference variable is an alias, that is, it is another name for an existing variable. Once a reference is initialized as a variable, you can use the reference name or variable name to point to the variable.
References can easily be confused with pointers, and there are three main differences between them:
Imagine that the variable name is a label that the variable is attached to the memory location, and you can think of the reference as a second label that the variable is attached to the memory location. T herefore, you can access the contents of the variable by name or reference of the original variable. For example:
int i = 17;
We can declare a reference variable for i, as follows:
int& r = i;
In these statements, read as a reference. T herefore, the first declaration can read "r is an integer reference that initializes to i" and the second declaration can read "s is a double reference that initializes 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 typically used for function argument lists and function return values. Here are two important concepts related to C++ references that C?programmers must be aware of:
concept | describe |
---|---|
Use reference to parameters | C ++ supports the reference to the parameter transmission to the function, which is more secure than the general parameter. |
Use the reference as a return value | You can return a reference from the C ++ function, just like returning other data types. |