三种传递方式有着不同的用法。
#include <iostream>
using namespace std;
// value pass
void change1(int n)
{
cout << "value pass -- the address of parameter is " << &n << endl; // what is showed is the address of copied parameter not the source address
n++;
}
// pass by reference
void change2(int &n)
{
cout << "pass by reference -- the address of parameter is " << &n << endl;
n++;
}
// pass by pointer
void change3(int *n)
{
cout << "pass by pointer -- the address of parameter is " << n << endl;
*n = *n + 1;
}
int main()
{
int n = 10;
cout << "the address of argument is " << &n << endl;
change1(n);
cout << "after change1() , n = " << n << endl;
change2(n);
cout << "after change2() , n = " << n << endl;
change3(&n);
cout << "after change3() , n = " << n << endl;
return 0;
}
指针传递本质上是值传递,将地址值传递给形参,形参开辟局部变量来处理地址。也就是说,实参的地址本身不会被修改。
程序在编译时分别将指针和引用添加到符号表上,符号表上记录的是变量名及变量所对应地址。指针变量在符号表上对应的地址值为指针变量的地址值,而引用在符号表上对应的地址值为引用对象的地址值。符号表生成后就不会再改,因此指针可以改变其指向的对象(指针变量中的值可以改),而引用对象则不能修改。
参考:
http://www.cnblogs.com/yanlingyin/