参考与指针

时间:2013-09-11 00:36:48

标签: c++ pointers reference

我认为现在是时候了解它的不同之处。我已经看到了如何使用这些,但教程有点模糊。我对语法以及如何在很小程度上使用它们有非常基本的了解。指针似乎总是有点可怕和令人困惑。我听说一旦你学会使用它们就很棒,我想要一些伟大的东西:)。那么我该怎样才能使用这些呢?我应该在什么时候使用这些呢?还有一件事,我正在使用C ++。

谢谢!

1 个答案:

答案 0 :(得分:1)

即使我同意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;