c++ - 引用与指针

标签 c++ pointers reference

<分区>

我想是时候了解其中的区别了。我已经看到如何使用这些,但教程有点含糊。我对语法以及如何在很小的范围内使用它们有非常基本的了解。指针总是看起来有点可怕和令人困惑。我听说一旦你学会使用它们就会很棒,我想要一些很棒的东西 :)。那么我该如何使用这些以及我应该在什么时候使用它们呢?还有一件事,我正在使用 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/

相关文章:

C++对删除错误

c++ - 在 C++ 模板中使用运算符

string - 使用 reflect.StringHeader 将字节转换为字符串仍然分配新内存?

javascript - 存储对 DOM 元素的引用

c++ - 我应该使用函数指针来选择构造函数中的实现吗?

c++ - 触发了一个断点(析构函数),类模板类型是它自己的一个版本?

c++ - 如何在 Windows 上部署 Qt 应用程序?

函数类型冲突?

c++ - 错误 : No instance of constructor matches the argument list

C++ ifstream::read 混淆