C + + - Reference

C++ quote:

A reference in C + + is an alias, that is to say, it is another name of an existing variable. Once the reference is initialized to a variable, the reference name or variable name can be used to point to the variable

C + + references and pointers:

References and pointers are easy to confuse, but there are the following differences between them:

1. There is no empty reference in the reference. The reference must be connected to a legal space

2. Once a reference is initialized as an object, it cannot point to another object

3. References must be initialized at creation time

Basic syntax of reference:

1. Initialization:

int i = 10;
int &a = i;//Type & alias = original name
//Reference to array
int arr[5] = {1,2,3,4,5};
//Method 1:
int (&prArr)[5] = arr;
//Mode two:
typedef int(ARRAYREF)[5];//An array of type int with 5 elements
ARRAYREF &prArr1[5] = arr;

2. Parameter transfer:

int main() {
	int a = 10;
	int b = 12;

void swap3(int &x, int &y) {//int &x <==>int &x = a;
	int temp = y;
	y = x;
	x = temp;

matters needing attention:

1. Must refer to a legal space

Do not return a reference to a local variable. If the return value is a reference, the function call can be used as an lvalue

Essence: the essence of reference in C + + is a pointer constant

int a = 10;
int &b = a;
//Compiler automatically converts to int * const B = & A;
b = 20;
//Internal discovery B is a reference, automatically converted to * b = 20 

Reference to pointer:

void AllocatePointer(Teacher** teacher) {
	*teacher = (Teacher *)malloc(sizeof(Teacher));
	(*teacher)->m_age = 20;

void AllocateReference(Teacher*& tea) {//Teacher*& tea = teacher;
	tea->m_age = 30;                   //Teacher** const tea = &teacher;

int main() {
	Teacher a;
	Teacher* teacher = NULL;//Define a pointer variable to the Teacher structure type
	teacher = &a;
	Teacher** t = &teacher;//
	cout << teacher->m_age << endl;
	cout << teacher->m_age << endl;

Reference to constant:

Literal quantity cannot be assigned to a reference, but can be assigned to a const reference

const int &re = 10;


Posted by longhorn14 on Wed, 06 Nov 2019 13:25:34 -0800