分类:
2012-10-09 22:06:03
原文地址:值传递、指针传递和引用传递 作者:apple_guet
要理解值传递、指针传递和引用传递的区别,主要要理解函数的实参和形参,函数的作用域(自动变量、栈),内存的布局以及指针和引用的特点。这里主要总结三种参数传递方式使用的主要场合。
后来复习的时候又写了一个DEMO,这个不需要解释,大家都懂的。
#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#include <iostream>
#include <sys/timeb.h>
#include <ctime>
#include <climits>
using namespace std;
//交换参数-值传递
void SwapByVal(int v1,int v2)
{
int tmp = v2;
v2 = v1;
v1 = tmp;
}
//交换参数-引用传递
void SwapByRef(int &v1,int &v2)
{
int tmp = v2;
v2 = v1;
v1 = tmp;
}
//交换参数-指针传递
void SwapByPtr(int *v1,int *v2)
{
int tmp = *v2;
*v2 = *v1;
*v1 = tmp;
}
int _tmain(int argc, _TCHAR* argv[])
{
//值传递
int a = 10 , b = 20;
cout << "值传递前:a = " << a << " ; b = " << b << endl;
SwapByVal(a,b);
cout << "值传递后:a = " << a << " ; b = " << b << endl;
//复位-引用传递
a = 10 , b = 20;
cout << "引用传递前:a = " << a << " ; b = " << b << endl;
SwapByRef(a,b);
cout << "引用传递后:a = " << a << " ; b = " << b << endl;
//复位-指针传递
a = 10 , b = 20;
cout << "指针传递前:a = " << a << " ; b = " << b << endl;
SwapByPtr(&a,&b);
cout << "指针传递后:a = " << a << " ; b = " << b << endl;
system("pause");
return 0;
}