当前位置:网站首页>The main difference between pointer and reference
The main difference between pointer and reference
2022-04-23 05:27:00 【What’smean】
The pointer “ Point to ” An object in memory , And quote “ Bound to the ” An object in memory , They all implement indirect access to other objects , There are two main differences between the two :
First of all , The pointer itself is an object , Allows assignment of values and values to pointers , And in the life cycle of the pointer, it can point to several different objects ; Reference is not an object , Cannot rebind reference to another object .
second , The pointer does not need to have an initial value at definition time , Like other built-in types , If a pointer defined within the scope of a block is not initialized , Will also have an uncertain value ; The reference must be given an initial value at the time of definition .
The code is :
#include<iostream>
using namespace std;
void swap1(int &a,int &b){ // Reference implementation
int temp=0;
temp = a;
a = b;
b = temp;
};
void swap2(int *a,int *b){ // Pointer implementation
int temp=0;
temp = *a;
*a = *b;
*b = temp;
};
int main(){
int i=5,j=10;
int*p=&i;
cout<<p<<"\t"<<*p<<endl;
p=&j;
cout<<p<<"\t"<<*p<<endl;
*p=20;
cout<<p<<"\t"<<*p<<endl;
j=30;
cout<<p<<"\t"<<*p<<endl;
swap1(i,j);
cout<<i<<"\t"<<j<<endl;
cout<<p<<"\t"<<*p<<endl;
swap2(&i,&j);
cout<<i<<"\t"<<j<<endl;
cout<<p<<"\t"<<*p<<endl;
return 0;
}
Output results :
0x66ff24 5
0x66ff20 10
0x66ff20 20
0x66ff20 30
30 5
0x66ff20 5
5 30
0x66ff20 30
Please press any key to continue . . .
版权声明
本文为[What’smean]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220544124497.html
边栏推荐
猜你喜欢
Modèle axé sur le domaine DDD (III) - gestion des transactions à l'aide de Saga
Excel 2016 打开文件第一次打不开,有时空白,有时很慢要打开第二次才行
弘玑Cyclone RPA为国金证券提供技术支撑,超200个业务场景实现流程自动化
Quick app bottom navigation bar
相机成像+单应性变换+相机标定+立体校正
如果我是pm之 演出电影vr购票展示
2021-11-08
Create a tabbar component under the components folder, which is public
[no title] Click the classification jump page to display the details
How to set the initial value of El input number to null
随机推荐
Output string in reverse order
My old programmer's perception of the dangers and opportunities of the times?
Simple and basic use of switch and if
egg中的cors和proxy(づ ̄3 ̄)づ╭~踩坑填坑的过程~ToT~
C# ,类库
Solve the problem of JS calculation accuracy
Tslint annotations ignore errors and restful understanding
How to set the initial value of El input number to null
To understand Devops, you must read these ten books!
String class understanding - final is immutable
使用宝塔+xdebug+vscode远程调试代码
Uncle wolf is looking for a translator -- Plato -- ongoing translation
node中的redis使用--ioredis
varnish入门
Uniapp wechat sharing
Edit, cancel, pull up menu
The 2021 IT industry project management survey report was released!
JSP -- Introduction to JSP
Data bus realizes the communication between brother components
When is it appropriate for automated testing? (bottom)