object * x 和 object& 有什么区别x 在 c++
可能的重复:
C++中指针变量和引用变量的区别 < /p>
假设我正在尝试将对对象 x 的引用传递给 C++ 函数...
之间有什么区别
pass(Object * x){
}
和
pass(Object& x){
}
,当使用不同的方法声明指针/引用时,如何访问实际对象本身...
例如,如果我有 Object * x,我将如何实际访问 x 引用的实际对象(
与 Object& 相同) x
Possible Duplicate:
Difference between pointer variable and reference variable in C++
suppose I'm trying to pass a reference to object x to a c++ function...
what's the difference between
pass(Object * x){
}
and
pass(Object& x){
}
and how would you access the actual object itself when the pointer/reference is declared using the different methods...
for instance if I have Object * x, how would I actually access the actual object that is referenced by x
same with Object& x
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个是传递指针。第二种是按引用传递。
至于使用,指针在使用之前必须被“取消引用”。这是通过
*
和->
运算符完成的:引用没有这样的限制:
但是,引用在其整个生命周期中只能指向单个对象,而指针可以更改目标并(如 John 在下面提到的)指向“无”(即
NULL
、0
或在 C++0x 中为nullptr)。 C++ 中不存在 NULL 引用这样的东西。
由于引用更易于使用且不易出错,因此除非您知道自己在做什么(指针是一个非常困难的主题),否则更喜欢它们。
The first is a pass by pointer. The second is a pass by reference.
As for usage, a pointer must be "dereferenced" before it can be used. That is done with the
*
and->
operators:References have no such restriction:
However, references can only point to a single object for their whole lifetime, while pointers can change target and (as John mentionned below) point to "nothing" (that is,
NULL
,0
or, in C++0x,nullptr
). There is no such thing as aNULL
reference in C++.Since references are easier to use and less error-prone, prefer them unless you know what you're doing (pointers are a pretty tough subject).
通过引用传递意味着调用者应保证引用的对象有效。传递指针通常需要函数检查指针是否为NULL。
通过引用传递还意味着函数不关心对象的生命周期。通过指针传递可能需要函数来破坏对象。
因此,显然,通过引用传递语义清晰,可能性较小,不易出错。
Pass by reference means the caller should guarantee that the referred object is valid. Pass by pointer usually requires the function to check whether the pointer is NULL.
Pass by reference also means the function don't care about the lifecycle of the object. Pass by pointer may require the function to destruct the object.
So, apparently, pass by reference has clear semantics, less possibility, less error-prone.