0

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

谢谢!

4

1 回答 1

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;  
于 2013-09-11T00:48:53.813 回答