3

可能重复:
'&' 运算符在 C++ 中的作用是什么?

今天在我的 CS 课上,老师向我们展示了一些函数和模板的示例,并且一些函数原型在参数列表中具有与号,如下所示:

void exchange( T & x, T & y ) ; // prototype

这意味着什么?我应该用它做什么?

4

2 回答 2

4

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.

于 2012-02-28T20:07:36.217 回答
1

The & means 'reference to' - x is a reference to a T, not a copy.

于 2012-02-28T20:08:42.453 回答