<分区>
我想是时候了解其中的区别了。我已经看到如何使用这些,但教程有点含糊。我对语法以及如何在很小的范围内使用它们有非常基本的了解。指针总是看起来有点可怕和令人困惑。我听说一旦你学会使用它们就会很棒,我想要一些很棒的东西 :)。那么我该如何使用这些以及我应该在什么时候使用它们呢?还有一件事,我正在使用 C++。
谢谢!
<分区>
我想是时候了解其中的区别了。我已经看到如何使用这些,但教程有点含糊。我对语法以及如何在很小的范围内使用它们有非常基本的了解。指针总是看起来有点可怕和令人困惑。我听说一旦你学会使用它们就会很棒,我想要一些很棒的东西 :)。那么我该如何使用这些以及我应该在什么时候使用它们呢?还有一件事,我正在使用 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;
关于c++ - 引用与指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18730910/