Novice: reference types under C++

  • 2020-05-05 11:09:51
  • OfStack


A reference type is also called an alias, and it's a very interesting thing. Under c++ you can think of it as another kind of pointer, and we can also manipulate objects indirectly by reference types, which are mainly used for formal arguments to functions, and we usually use them to pass class objects to a function.

The reference object is defined as a type name with an ampersand and a name. For example :(int &test;) Here we define a reference of type int called test, but int &test; This method cannot be compiled successfully, because the definition of the reference must be assigned to the application at the same time. .

#include   < iostream >  
using   namespace   std;  

void   main(void)  
{  

int   a=10;  
int   &test=a;  
test=test+2;  

cout   < <   &a   < <   "|"   < <   &test   < <   "|"   < <   a   < <   "|"   < < test   < <   endl;  

cin.get();  
}

Watch and compile and run the above code and you will see that the address of &a and &test are the same, and the value of a and test are the same!

In combination with the content of the previous tutorial, let's talk about the content of the const reference. It is important to note that the reference with the const decoration is just as easy to confuse the concept as the previous tutorial!

The special thing about const for references is that you can initialize different types of objects, which is impossible for normal variable operations. Here's an example:

#include   < iostream >  
using   namespace   std;  

void   main(void)  
{  

int   a=10;  
//double   &test   =   a   +   1.2f;   // this sentence is wrong!  
const   double   &test   =   a   +   1.2f;  

cout   < <   &a   < <   "|"   < <   &test   < <   "|"   < <   a   < <   "|"   < < test   < <   endl;  

cin.get();  
}

The above code is enough to explain the problem, which is the benefit of const decoration, but a smart person will find a problem when the output is different, that is, the output of a and test values are different, according to the first said reason should be able to change the value of a, why can it be changed here?

The idea is that the const modified reference changes inside the compiler like this.

int   a=10;  
const   double   &test   =   a   +   1.2f;

Such a piece of code is considered by the compiler to be

in the following way

int   a=10;  
int   temp   =   a;  
const   double   &test   =   temp   +   12.f

Here is actually the a value is assigned to a temporary temp variables, and then obtained test is temp + 12. f temp change rather than a, so has been a and test shows the value of the different situation, here it is important to pay special attention to, this is a very confusing place, be especially careful when writing programs, in order to avoid the problem, but check out why


Related articles: