多次下标std::array是如何工作的

How does subscripting std::array multiple times work?

本文关键字:工作 何工作 次下标 std array      更新时间:2023-10-16

即使所有operator[]返回都是引用,但不使用任何代理对象(如图所示),多次为std::array进行下标是如何工作的?

示例:

#include <iostream>
#include <array>
using namespace std;
int main()
{
    array<array<int, 3>, 4> structure;
    structure[2][2] = 2;
    cout << structure[2][2] << endl;
    return 0;
}

这是如何/为什么工作的?

您只需调用structure.operator[](2).operator[](2),其中第一个operator[]返回对structure中应用第二个operator[]的第三个数组的引用。

请注意,对对象的引用可以像对象本身一样使用。

正如您所说,structure[2]提供了对外部数组元素的引用。作为一个引用,它可以被视为完全相同类型的对象。

该元素本身就是一个数组(array<int,3>),可以对其应用另外的[]。这提供了对内部数组中类型为int的元素的引用。