数组[]运算符返回参考,因此如何更改其值

Array [] operator returns a reference, so how can you change its value?

本文关键字:何更改 运算符 返回 参考 数组      更新时间:2023-10-16

正如我在此处阅读的: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]可以看作是存储在数组中某个位置的任何对象的不同名称。因此,任务如上所述。