“&”表示C++中的引用调用,表示对参数的修改结果需要“带回来”(带到主函数中利用),在C语言中采用指针也会达到同样的效果。
相关实例代码:
#include<iostream>
using namespace std;
void test1(int x)
{
x=1024;
cout<<"函数1内部x的值为:"<<x<<endl;
}
//引用调用,将参数的修改结果带到“主函数”当中
//c++的引用直接用&
void test2(int &x)
{
x=1024;
cout<<"函数2内部x的值为:"<<x<<endl;
}
//C语言的引用如下
void test3(int x)
{
int *p=&x;
*p=1024;
cout<<"函数3内部x的值为:"<<x<<endl;
}
int main()
{
int x=1;
cout<<"x初始值为:1"<<endl;
test1(x);
cout<<"调用函数1后,x的值为:"<<x<<endl;
test2(x);
cout<<"调用函数2后,x的值为:"<<x<<endl;
test3(x);
cout<<"调用函数3后,x的值为:"<<x<<endl;
return 0;
}
运行结果如下: