The reference type is also called an alias. It is very interesting. In c ++, You can regard it as another pointer. Through reference types, we can also indirectly manipulate objects. The reference types are mainly used in the form parameters of functions, we usually use it to pass class objects to a function.
The referenced object is defined by adding & Symbol and name to the type name. For example: (int & test;) Here we define a reference of the int type named test, but the int & test method cannot be compiled successfully, because the referenced definition must assign values to the application at the same time, the assignment here does not mean to pass the value of the variable to the reference, but to point the reference to the variable, write it as follows: (int & test = variable name ;).
# Include <iostream>
Using namespace std;
Void main (void)
{
Int a = 10;
Int & test =;
Test = test + 2;
Cout <& a <"|" <& test <"|" <a <"|" <test <endl;
Cin. get ();
}
Observe and compile and run the above code. You will find that the addresses of & a and & test are the same, and the values of a and test are also the same!
In combination with the content of the previous tutorial, let's take a look at the reference content of const. Here we should pay special attention to it. Like the reference with const modification in the previous tutorial, It is also easy to confuse the concept!
If the const modifier is used for reference, the secret of const is that it can be initialized for different types of objects, however, it is impossible to operate on common variables. Let's look at an example:
# Include <iostream>
Using namespace std;
Void main (void)
{
Int a = 10;
// Double & test = a + 1.2f; // This sentence is incorrect!
Const double & test = a + 1.2f;
Cout <& a <"|" <& test <"|" <a <"|" <test <endl;
Cin. get ();
}
The above code is enough to explain the problem. This is the benefit of const modification, but smart people will find a problem in output, that is, the output of the values of a and test is different, according to the first principle, the value of a can be changed. why can it be changed here?
The truth is that the reference modified by const changes in the compiler.
Int a = 10;
Const double & test = a + 1.2f;
Such a piece of code is considered by the compiler as follows:
Int a = 10;
Int temp =;
Const double & test = temp + 12.f
In fact, the value of a is assigned toTemporaryThe temp variable is obtained by test, but temp + 12.f changes temp rather than a, so the values displayed by a and test are different. Pay special attention to the following, this is a very confusing place, so you should be very careful when writing the program, so as not to check the problem but why