[C++] 3-1.1 c++ reference

1. What is a reference

The reference is an "alias" of the referenced variable. When reading and writing the reference, it is equivalent to directly reading and writing the referenced variable itself.

The understanding of "alias":
There is a variable defined in advance, and then there is an alias for this variable;
that is, the reference must be attached to an existing variable.

In addition, a variable can have multiple "alias", but each "alias" can only be given to one variable;
this does not conflict: variables can have multiple aliases, but the aliases cannot conflict!

2. Statement of reference

The quoted declaration is as follows:

type& referenceName = variable;

Among them,
"type" is a certain data type, such as "int";
referenceName is the name of the referenced variable;
variable is the referenced variable.

Note: The
reference must be initialized when it is declared, so variable must be a variable defined in advance.

Notes on &:
& (pronounced as an and symbol) itself is a symbol for taking an address. When & is placed in the definition of a variable, the & symbol is a reference, not an address!

Example:

# include <iostream>

int main()
{
    
    
	int x, & rx = x; //等价 int x;int&  rx = x;
	rx = 5;
	std::cout << x << std::endl; //输出数字5
	return 0;
}

3. The nature of the citation

-3.1 The reference must be initialized at the time of declaration;
-3.2 Read and write operations by reference actually act on the original variable;
-3.3 Once the reference is initialized, the reference name cannot be assigned to other variables;

4. Pass by reference

When we declare a function, its parameters are called formal parameters, or formal parameters for short;
when calling a function, the parameters passed are called actual parameters, or actual parameters for short;

When the formal parameter is a reference type: Pass by reference;

For functions passed by reference:
you only need to pass ordinary variables when calling;
change the value of the reference variable in the called function, then the value of the actual parameter is changed (the formal parameter of the reference type can be regarded as the actual parameter variable itself );

5. Multiple cited examples

#include <iostream>

int main() {
    
    
	int a{
    
     0 }, b{
    
     1 };
	int& r{
    
     a };//引用在声明的同时就要初始化,r是a的别名;
	std::cout << "1、a=" << a << " b=" << b << std::endl;
	r = 42;

	std::cout << "2、a=" << a << " b=" << b << std::endl;

	r = b;

	std::cout << "3、a=" << a << " b=" << b << std::endl;

	int& r2{
    
     a };//继续给a起别名;

	r2 = 77;
	std::cout << "4、a=" << a << " b=" << b << std::endl;

	int& r3{
    
     r };//给r起别名,即给a起别名;

	r3 = 66;
	std::cout << "5、a=" << a << " b=" << b << std::endl;

	return 0;
}

Run as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/jn10010537/article/details/115286161