指针“指向”内存中的某个对象,而引用“绑定到”内存中的某个对象,它们都实现了对其他对象的间接访问,二者的区别主要有两方面:
第一,指针本身就是一个对象,允许对指针赋值和铂贝,而且在指针的生命周期内它可以指向几个不同的对象;引用不是一个对象,无法令引用重新绑定到另外一个对象。
第二,指针无须在定义时赋初值,和其他内置类型一样,在块作用域内定义的指针如果没有被初始化,也将拥有一个不确定的值;引用则必须在定义时赋初值。
代码体现:
#include<iostream>
using namespace std;
void swap1(int &a,int &b){ //引用实现
int temp=0;
temp = a;
a = b;
b = temp;
};
void swap2(int *a,int *b){ //指针实现
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;
}
输出结果:
0x66ff24 5
0x66ff20 10
0x66ff20 20
0x66ff20 30
30 5
0x66ff20 5
5 30
0x66ff20 30
请按任意键继续. . .