引用实际上就是传个参数的地址给它。在你的第一个类子中,x和a实际上指得是同一个内存地址,y和b也一样。所以x,y改变了,a,b也得改变。而你的第二个例子,则是传值,x 和 a 是不同的变量,两个变量的内存地址也不一样。只不过在调用时把a的值赋给x。当x的值改变时,a的值还是原来的。同理,y和b也一样。
In C++ , the parameter for the function call is passed by value, any change to the parameter in the function have no effect after the function exit.but if you pass the reference, it's similar with the pointer, the refered variable are bounded with the refering variable, any change to the refering variable will have the same effect to the refered variable.Hope this help.
在c++也有区别用*是声明一个指针,&引用:是一个保存对象地址的变量,
但是在语法上和对象一样操作,。还是有一点的差别
}
any change to the parameter in the function have no effect after
the function exit.but if you pass the reference, it's similar with the pointer, the
refered variable are bounded with the refering variable, any change
to the refering variable will have the same effect to the refered
variable.Hope this help.
就像一个人可能有多个名字,比如说起诸葛亮,我们都知道是谁,而提起诸葛孔明,实际上指的是同一个人,只不过叫法不一样而已。看这个例子:
void Swap(int & x,int & y) // 声明是参数引用当调用这个函数时
int a=2, b=3;
...
Swap(a,b); // a,b是作为被引用的变量传人函数:
此时函数的参数x将作为变量a的别名(实际上x和a都是指同一个变量,只不过叫法(名字)不一样而已),
参数y将作为变量b的别名(y和b都是指同一个变量)再看函数里面:
{ int temp=x; x=y; y=temp; }
显然这时x就是变量a,y就是变量b。交换x、y也就是交换了变量a、b
而普通的以传值参数作为函数的参数时,就有很大的不同:
void Swap(int x,int y) // 函数参数声明为传值参数
在函数体内:
{ int temp=x; x=y; y=temp; }
参数x(或y)与变量a(或b)不是同一个东东,只不过它们有着相同的内容而已
比如这样:
int i=3, j=7;
i=j; // i和j不是同一个东东,但是它们现在有了相同的内容同样的道理:作为传值的Swap函数,其参数x,y在被调用时(Swap(a, b)),只不过把a的内容赋给了x,b的内容赋给了y;
因此交换时只交换了参数x,y的内容,而非a,b