C ++: references

1. The definition of reference:
a reference variable is an existing alias. By indirect reference can access the variable. Pointer can also indirectly access variables, but relative to the reference pointer in use more secure. The main purpose of reference to describe the function parameters and return values.
When defining a reference type variable, you need to initialize a variable that already exists, so it was bound to reference that variable. Changes to the references that changes to the variables of which it is bound.
Syntax:
Data Type & referenced variable name = variable name
Note:
(1) type and the data type should be of the same reference variable
(2) is a binary operator &
(3) the variable name is a variable defined
Example:
int X;
int & r = X;
explained:
(1) the reference variable (x) and the reference data type variable (r) is the same type of data, are int
(2) in a defined reference variable r before, x is already defined.
2. Description of the reference variable
is defined a reference variable after the system does not allocate space for the reference variable, and the variable reference variable is referenced with the same address, so in this case it is bound in the reference variable, changes to the reference It is bound to make changes to its variable, whereas empathy.

#include<iostream>
using namespace std;
int main(){
	int x=3;
	int &r=x;
	cout<<"x = "<<x<<"\t&x = "<<&x<<"\n";
	cout<<"r = "<<r<<"\t&r = "<<&r<<"\n";
	r=5;
	cout<<"x = "<<x<<"\t&x = "<<&x<<"\n";
	cout<<"r = "<<r<<"\t&r = "<<&r<<"\n";
	return 0;
}

[Run Results]
Here Insert Picture Description
From the above examples, with reference to the reference variables point to the same address, and modification is the modification of the reference variable is a reference value.
3. Chang references:
means that when modified by const define a reference variable, in which case reference is often defined reference
Syntax:
const data type variable name = & reference variable;
plus const is prevented to change the value of the variables by reference, by itself, but it can be variable to change the contents, because the variable is not modified by const
Example:

#include<iostream>
using namespace std;
int main(){
	int i=100;
	const int & r=i;
	r=220;
	return 0;
}

The results of program error.
Here Insert Picture Description
At this time, if the attempt to change the value of i is changed directly by itself i as i = 100.

Published 31 original articles · won praise 2 · Views 3844

Guess you like

Origin blog.csdn.net/weixin_44652687/article/details/100876306