HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Reference variable is an alias, that is to say, it is a name already exists in another variable. Once the reference is initialized to a variable, you can use the reference name or variable name to point to variables.
It is easy to confuse with the pointer references, there are three main differences between them:
Imagine variable name is a variable in the memory location of the subsidiary label, you can reference as a variable in the subsidiary in the second memory location tag. Therefore, you can access the variable name or a reference to the content through the original variable. E.g:
int i = 17;
We can refer to the variable i is declared as follows:
int& r = i;
In these statements, & read asreferences.Therefore, the first statement can be read as "r is an integer i is initialized to a reference to" the second statement can be read as "s reference is initialized to a double type of d." The following example uses int and double quote:
#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 argument lists and function return values. The following lists the C ++ programmer must clear two with C ++ references related key concepts:
概念 | 描述 |
---|---|
把引用作为参数 | C++ 支持把引用作为参数传给函数,这比传一般的参数更安全。 |
把引用作为返回值 | 可以从 C++ 函数中返回引用,就像返回其他数据类型一样。 |