引用与指针
References vs. Pointers
我认为是时候了解其中的区别了。 我已经看到了如何使用这些,但教程有点模糊。 我对语法以及如何在很小的范围内使用它们有非常基本的了解。 指针似乎总是有点可怕和混乱。 我听说一旦你学会使用它们,它们就很棒,我想要一些很棒的:)。 那么我如何使用它们,我应该在什么时候使用它们呢? 还有一件事,我正在使用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++为单位)
- 从 unique_ptr::get 发送指针作为指针引用进入函数
- 指针/引用的 CLion 格式
- 使用模板专用化来比较指针引用
- 如何保存指向抽象基类的指针/引用,但在 c++ 中仍然可以复制
- C++初始化指针/引用/复制细微差别
- 用数组或指针引用函数?
- 指针范围问题和返回类中封装的指针向量内的指针引用
- 强制转换为指针引用是否会导致未定义的行为
- 访问由 void 指针引用的结构的成员
- C 为什么当先前的步骤引发异常时,std :: shared_ptr的指针引用会被破坏
- 动态指针引用数组由三元运算符返回值,但有异常
- 悬空指向 int 和 char* 常量的指针/引用
- C++ 二维数组和指针引用
- 通过使用指针/引用,在C++中使用向量加快计算速度
- C++非类型模板模板到函数指针/引用