current position:Home>C + + reference

C + + reference

2022-01-27 00:27:12 Taiyi TT

1) Basic use : Alias variables

      data type & Alias = Original name ;

int main()
{
 int a=10;
 int &b=a;//a and b All point to the same block of memory 
  b=20;
}

2) matters needing attention :

You have to initialize int &b; FALSE

Once the reference is initialized , Can't be changed

int main()
{
  int a=10;
  int &b=a;
  int c=20;
   b=c;// Assignment operation , Instead of changing the alias . hold c The value is assigned to a and b
}

3) Reference as function parameter

effect : When a function passes parameters , You can use reference technology to make formal parameters modify arguments

advantage : You can optimize the pointer and modify the instance

int swao(int &a,int &b)//a and b They are aliases of arguments , Modifying formal parameters is actually modifying arguments 
{
 int t=a;
 a=b;
 b=t;
}// reference , Parameter modification argument 

4) Reference is the return value of the function

Don't return references to local variables

int& test1()
{ 
 int a=10;
 return a;
}

int main()
{
 int &ret=test1();
 cout<<ret<<endl;// Type the correct value for the first time , The compiler is reserved 
 cout<<ret<<endl;// The second result is wrong , because a Your memory has been freed 
}

The function can be called as an lvalue  

int& test1()
{ 
 static int a=10;// Static zone : The data in the global area is released after the program is finished 
 return a;
}

int main()
{
 int &ret=test1();
 cout<<ret<<endl;
 text1()=1000;// Made a a=1000 The operation of 
 // If the return value of a function is a reference , This function call can be used as an lvalue 
} 

5) The essence : constant pointer ( Once initialized , There can be no change )

int& ret=a;// Will automatically convert to int* const ret =&a;

6) const reference :

Constant references are used to decorate formal parameters , Prevent misoperation .

In the function parameter list , You can add const Modified parameter , Prevent formal parameters from changing arguments .

int main()
{
 int a=10;
 int& ref=10;//err A reference must refer to a legal memory space 
 const int& ref=10;// The compiler modified the code  int temp=10;const int& ref=temp;
 ref=10;// Join in const Can't be modified 
}
void show(const int& val)
{
 val=1000;//err val Cannot be modified 
}

int main()
{
 int a=10;
 show(a);
}

 

 

 

copyright notice
author[Taiyi TT],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270027091609.html

Random recommended