C ++ references
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.
C ++ pointer vs reference
It is easy to confuse with the pointer references, there are three main differences between them:
- The absence of a null reference. Reference must be connected to a legitimate memory.
- Once a reference is initialized to a target, it can not be directed to another object. Pointer can point at any time to another object.
- Reference must be initialized when created. Pointer can be initialized at any time.
C ++, create a reference
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++ 函数中返回引用,就像返回其他数据类型一样。 |