C++指针和引用的区别
指针、引用程序实践
源代码
#include <iostream>
using namespace std;
void maopapOrder(int arr[]){
for(int i=0;i<2;i++){
for(int j=0;j<2-i;j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void orderMethod1(int a,int b,int c){
int arr[3] = {a,b,c};
maopapOrder(arr);
a = arr[0];
b = arr[1];
c = arr[2];
cout << "inside int type : " << a << " " << b << " " << c << endl;
}
void orderMethod2(int* a,int* b,int* c){
int arr[3] = {*a,*b,*c};
maopapOrder(arr);
*a = arr[0];
*b = arr[1];
*c = arr[2];
cout << "inside int* type : " << *a << " " << *b << " " << *c << endl;
}
void orderMethod3(int& x,int& y,int& z){
int arr[3] = {x,y,z};
maopapOrder(arr);
x = arr[0];
y = arr[1];
z = arr[2];
cout << "inside int& type : " << x << " " << y << " " << z << endl;
}
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "please input three integer values:" << endl;
cin >> a >> b >> c;
orderMethod1(a,b,c);
cout << "outside int type : " << a << " " << b<< " " << c << endl;
cout << "-----------------------------------------" << endl;
/*
orderMethod2(&a,&b,&c);
cout << "outside int* type : " << a << " " << b<< " " << c << endl;
cout << "-----------------------------------------" << endl;
*/
orderMethod3(a,b,c);
cout << "outside int& type : " << a << " " << b<< " " << c << endl;
cout << "-----------------------------------------" << endl;
return 0;
}
输出结果:
指针:
引用:
结果分析
从定义上讲
指针是一个变量,变量中保存的是某个对象的地址,指向内存中的某个存储单元。
引用实际上与它所绑定的变量共用一块内存空间,是它绑定的那个变量的一个别名。
从使用规则上讲
指针可以有多级指针,而引用只能有一级
指针可以不初始化,指向NULL,而引用在使用时必须初始化。
从作为函数参数传递上
值得注意的是,二者皆可达到通过函数中的操作修改原变量值的效果,只是:
指针作为函数参数时,要求变量将地址传入,对指针的指向值的修改就是对原变量值的修改。
引用作为函数参数时,可以理解为就是将原变量传入(因为二者共用一块内存空间),对引用的修改当然也可以等效到引用绑定的原变量上。
但是,引用本身不需要开辟空间,所以在运行的时空效率上更好。
更多相关内容请参见