[Basic knowledge of C++] Analysis of knowledge points quoted in C++

References in C++

Referenced concept

The function of establishing a reference is usually to give another name to the variable, and the reference of the variable is usually considered as an alias of the variable.

When declaring a reference, it must be initialized with another variable. E.g:

int i=5;
int j=&i;               //声明j是一个整型变量变量的引用,并用i将其初始化。

Here j can be regarded as an alias of variable i. After such a declaration, i and j have the same function and represent the same variable. The operation performed on it is also equivalent. For example, if the value of j is changed, the value of i will also change accordingly.

The relationship between variables and references

#include<iostream>
using namespace std;
int main()
{
	int i;
	int &j = i;
	i = 30;
	cout << "i=" << i << ' ' << "j=" << j << endl;
	j = 80;
	cout << "i=" << i << ' ' << "j=" << j << endl;
	cout << "变量i的地址是:" << &i << endl;
	cout << "引用j的地址是: " << &j << endl;
	return 0;
}

The results are as follows:

Insert picture description here

It can be seen that the values ​​of i and j are updated synchronously and use the same memory space.

Description

1. The reference name can be any legalized variable name. In addition to being used as the return value and parameters of the function, when declaring the reference, it must be initialized immediately and cannot be assigned after the declaration is completed.

2. The initial value provided for the reference can be a variable or a reference.

3. A pointer indirectly accesses a variable through an address, and a reference directly accesses a variable through a variable alias. Every time you use a reference, you don't need to write the dereference operator "*", so the use of reference can simplify the program.

4. A reference cannot be redeclared as a reference to another variable after initialization.

5. Not any type of data can be quoted, for example:

①, can not create a reference of type void;

②, can not create a referenced array:

int a[4]="abcd";
int &ra[4]=a;          //非法

③, the reference of the reference cannot be established, and the pointer to the reference cannot be established;

int a=10;
int &&b=a;             //非法
int &*c=a;             //非法

6. You can assign the referenced address to a pointer, at this time the pointer points to the original variable.

7. The reference operator "&" only plays this role when declaring the reference, and the "&" appearing in other occasions are used as the address operator.

In addition, there are many functions of reference, such as reference as a function parameter, as a function return value, and so on.

Guess you like

Origin blog.csdn.net/weixin_43962381/article/details/111183021