Use of C ++ references

Source: Internet
Author: User

1 reference definition
C ++ is an important extension of C When referencing. The function of referencing is to give the variable an alias.

For example:

Int;

Int & B = a; // declare that B is a reference of

After the above statement, B becomes the alias of a. both a and B have the same status and role.

To declare B as a reference, you do not need to create new units for B. B and a occupy the same storage unit in the memory. They have the same address.

 

# Include <iostream> using namespace std; int main () {& nbsp; int a = 10; & nbsp; & nbsp; int & B = a; // declare that B is a reference & nbsp; cout <"B =" <B <endl; & nbsp; a = A-5; & nbsp; & nbsp; cout <"B =" <B <endl; & nbsp; B = B-1; & nbsp; cout <"a =" <a <endl; & nbsp; & nbsp; return 0 ;}



 

 

 

In the program,

Declares that B is a reference of a, and then outputs B = 10;

Then reduce the value of a by 5, and then output B = 5, which means that B will change with the change of;

Then reduce the value of B by 1, and then output a = 4, indicating that a will change with the change of B.

When declaring a reference, you must initialize it at the same time, that is, declare the variable that it represents. After declaring that variable B is a reference of variable a, you can use B as the alias of variable a, and B cannot be referenced as another variable (alias ).

Declare references without initialization:

 

 
#include<iostream>   using namespace std;  int main(){           int a=10;           int &b;                         return 0;  }  #include<iostream>using namespace std;int main(){         int a=10;         int &b;                       return 0;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.