数组[]运算符返回参考,因此如何更改其值
Array [] operator returns a reference, so how can you change its value?
正如我在此处阅读的:http://www.cplusplus.com/reference/stl/array/operator []/
看来,说 a[2]
会返回 a
的第二个元素的内存地址(参考)。
那么
如何a[2]=5
有效的分配,因为这意味着我将a[2]
的内存地址更改为位置5(可能是可能的,但通常您想更改值,而不是地址)。除非=
操作员知道如何处理这种情况。
我知道它不会更改内存地址,所以这里发生了什么?
参考和指针之间的区别在于,引用是自动化的。因此,您不需要*(a[2]) = 5
。
以下代码显示以下内容:
int baseVar = 42; // This
int &sameVar = baseVar; // and this are the same memory
// with two different names.
int *pBaseVar = &baseVar; // This is separate memory that happens
// to point to the baseVar memory.
更改sameVar
或*pBaseVar
的要么会更改baseVar
本身。更改pBasevar
本身将不是影响 basevar
,它将仅导致以前指向其他位置。
封面下(尽管这当然是依赖于实施的,但basevar
可能(由编译器/代码)视为在特定地址的int
(例如0x12345678
),sameVar
也被认为是。<<<<<<<<<<<<<<<<<<
pBaseVar
被视为(例如)0x11112222
的指针,恰好包含 value 0x12345678
:
+------------+
pBaseVar (0x11112222) | 0x12345678 |--+
+------------+ |
+----------------------------------+
|
V +----+
baseVar (0x12345678) | 42 |
sameVar (same) | |
+----+
参考不是内存地址。将其视为同一对象的另一个名称:
int i = 42;
int& j = i; // j is another name for i
j = 55;
std::cout << i << "n"; // i now has value 55
因此,a[2]
可以看作是存储在数组中某个位置的任何对象的不同名称。因此,任务如上所述。
相关文章:
- C++:无法使用 "=" 运算符更改 std::p air 的值
- 如何将数组的重载运算符 [] 更改为 ()?
- 我们可以使用运算符重载来更改 Minus 的行为吗?
- 预处理器是否可以更改运算符重载功能的符号?
- 为什么括号在这种情况下无法更改c++运算符的优先级
- 在浮点值上否定运算符与提升::数学::更改符号
- C++中重载复合赋值运算符不会更改变量
- 为什么有条件编译运算符模板会更改另一个运算符的可用性?
- Const 仍然允许在运算符函数 c++ 下进行更改
- 重载时获取堆栈溢出 >> 运算符函数是为类调用的。我需要进行哪些更改?
- 为什么我不能通过在 cpp 中使用新运算符传递指针来更改值?
- 如何在 vim 的配色方案中更改运算符 (+- * / < >) 的颜色
- 更改对象并将其在同一表达式中使用它是不确定的行为,但是子表达式由逗号运算符分开
- 重载运算符->() 以更改被调用函数的返回值
- C ++如何使用带有[]运算符的fstream更改文件的字符
- C++ 链表:"->"运算符无法更改节点对象的内部值
- 是否保证标准提取运算符>>在失败时不会更改参数?
- 使用 [][] 运算符更改通用 2D 数组类的值
- 运算符 [][] 重载 - 更改值
- C++模板专用化:更改运算符()的返回类型