可能重复:
'&' 运算符在 C++ 中的作用是什么?
今天在我的 CS 课上,老师向我们展示了一些函数和模板的示例,并且一些函数原型在参数列表中具有与号,如下所示:
void exchange( T & x, T & y ) ; // prototype
这意味着什么?我应该用它做什么?
可能重复:
'&' 运算符在 C++ 中的作用是什么?
今天在我的 CS 课上,老师向我们展示了一些函数和模板的示例,并且一些函数原型在参数列表中具有与号,如下所示:
void exchange( T & x, T & y ) ; // prototype
这意味着什么?我应该用它做什么?
the & is for reference. In short that's something like a pointer, that can't be NULL. Wikipedia has something on this topic here.
References are cheap when they are used in function/method calls, since the object doesn't need to be copied in your function call. You still have the same syntax as if you had with a copied object. With pointers you would need to handle the special case, that the pointer is NULL.
That is a usual reason to use them. If I guess right and exchange means something like swap the tow objects x and y, the the cost of the function call is directly related to the cost of coping the object, so saving some copies may be a relevant optimization.
The &
means 'reference to' - x
is a reference to a T
, not a copy.