C++中指向引用的指针、指向指针的引用和指向指针的指针有什么区别?
哪里应该优先选择其中一个?
首先,对指针的引用就像对任何其他变量的引用一样:
void fun(int*& ref_to_ptr)
{
ref_to_ptr = 0; // set the "passed" pointer to 0
// if the pointer is not passed by ref,
// then only the copy(parameter) you received is set to 0,
// but the original pointer(outside the function) is not affected.
}
指向引用的指针在 C++ 中是非法的,因为与指针不同,引用只是一个允许程序员进行操作的概念aliases其他的东西。指针是一个记忆中的位置它有其他东西的地址,但引用不是。
如果您坚持将引用作为指针处理,那么最后一点可能不太清楚。例如。:
int x;
int& rx = x; // from now on, rx is just like x.
// Unlike pointers, refs are not real objects in memory.
int* p = &x; // Ok
int* pr = ℞ // OK! but remember that rx is just x!
// i.e. rx is not something that exists alone, it has to refer to something else.
if( p == pr ) // true!
{ ... }
从上面的代码中可以看出,当我们使用引用时,我们并不是在处理与其所引用的内容分离的东西。因此,引用的地址就是它所引用的内容的地址。这就是为什么没有所谓的引用地址之类的东西you正在谈论。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)