int dist(int a,int b)
int dist(int &a,int &b)
这两种有什么区别?第二种是引用吗?为什么都用第二种而不是第一种?效果不都一样吗?
int dist(int a,int b)
int dist(int &a,int &b)
这两种有什么区别?第二种是引用吗?为什么都用第二种而不是第一种?效果不都一样吗?
参数中&代表取地址,就是将你变量的地址传进去,如果函数中参数改变,那么刚刚传的变量也会跟着改变。例如:
int dist(int &a,int &b)
{
a=123;
b=123;
}
int main()
{
int x,y;
x=100,y=100;
dist(x,y);
cout<<x<<' '<<y<<endl;
return 0;
}
这时输出的不是100 100,而是123 123
因为参数会带着你刚才传进去的变量一起改变,知道了吗?