C++ variable reference | use variable reference

C++ variable references

C++ can use a reference to a data. Reference is an important extension of C++ to the C language. Reference is a new variable type. Its function is to give a variable an alias.

For example, to give the variable temp an alias change:

int temp;//定义整型变量temp
int &change=temp;//声明change是temp的引用

The above code declares that change is a reference to temp, that is, change is an alias of temp. After the above declaration, change and temp have the same function and both represent the same variable. & is a reference declarator and does not represent an address. Readers should not interpret it as The value of temp is assigned to the address of change.

Declaring the variable change as a reference type does not need to open up another memory unit to store the value of change. Change and temp occupy the same storage unit in memory, and they have the same address. Declaring that change is a reference to temp can be understood as: make the variable change have the address of the variable temp.

In C++, when declaring a reference type variable, you must initialize it at the same time, that is, declare which variable it represents. After declaring that the variable change is a reference to the variable temp, during the execution of the function in which they are located, the reference type variable change is always The representative variable temp is connected and cannot be used as a reference to other variables.

Classic case: C++ uses variable references.

#include<iostream>//预处理
using namespace std;//命名空间 
int main()//主函数 
{
    
    
  int temp;//定义变量 
  temp=10;//赋初值 
  int &change=temp;//引用 
  cout<<temp<<endl;//输出原来的 
  cout<<"-------"<<endl;//分隔符 
  cout<<change<<endl; //输出引用变量 
  return 0; //函数返回值为0;
}

After executing this program, it will output:

10
-------
10

--------------------------------
Process exited after 3.501 seconds with return value 0
请按任意键继续. . .

C++ uses variable references

More cases can go to the public account: C language entry to mastery

Guess you like

Origin blog.csdn.net/weixin_48669767/article/details/111609598