引用与指针

References vs. Pointers

本文关键字:指针 引用      更新时间:2023-10-16

我认为是时候了解其中的区别了。 我已经看到了如何使用这些,但教程有点模糊。 我对语法以及如何在很小的范围内使用它们有非常基本的了解。 指针似乎总是有点可怕和混乱。 我听说一旦你学会使用它们,它们就很棒,我想要一些很棒的:)。 那么我如何使用它们,我应该在什么时候使用它们呢? 还有一件事,我正在使用C++。

谢谢!

尽管我同意Mooing Duck在这里的一个可能揭示的小样本:

int nValue = 5;
/* 
 * &rfValue is a reference type, and the & means reference to.
 * references must be given a value upon decleration.
 * (shortcut like behaviour)
 * it's better to use reference type when referencing a valriable,
 * since it always has to point to a valid object it can never
 * point to a null memory. 
 */
int &rfValue = nValue;
/* This is wrong! reference must point to a value. it cannot be
 * null.
 */
//int &rfOtherValue; /* wrong!*/
/* same effect as above. It's a const pointer, meaning pValue 
 * cannot point to a different value after initialization.
 */
int *const pValue = &nValue; //same as above
rfValue++;  //nValue and rfValue is 6
nValue++;   //nValue and rfValue is 7
cout << rfValue << " & " << *pValue << " should be 7" << endl;