简体   繁体   English

如何重载下标运算符 [] 以引用 2d STL 数组?

[英]How to overload subscript operator [] to reference 2d STL array?

I am trying to create an overloaded operator for my class, my class contains a 2d array container.我正在尝试为我的班级创建一个重载运算符,我的班级包含一个二维数组容器。 I want use the operator as follows: fooClass a;我想按如下方式使用运算符:fooClass a; a[i][j] = 4; a[i][j] = 4; i don't want to use it like a[i, j], a(i, j) or call a function to input or output an element.我不想像 a[i, j], a(i, j) 那样使用它或调用函数来输入或输出元素。 Is is possible?有可能吗?

Chaining the call wont work since the first returns pointer to array, and the second should return an element in an array ie a float.链接调用不起作用,因为第一个返回指向数组的指针,第二个应该返回数组中的一个元素,即浮点数。

my class looks something like this:我的课看起来像这样:

class foo
{
    public:
    foo();
    ~foo();

    foo& operator=(const foo&rhs);
    foo& operator=(const foo&&rhs);
    foo& operator=(std::initializer_list<std::initializer_list<float>> il); 
    friend std::ostream& operator<<( std::ostream& os, const foo&rhs);
    std::array<float, 3>& operator[](const int & rhs); <<<<HERE<<<< What should it return?

    private:
    std::array<std::array<float, 3>, 3> matrix;
};


int main()
{
    foo a;
    a = {{1,2,3},{4,5,6},{7,8,9}};
    a[1][2] = 13;
    cout << a[1][2] << endl;


    return(0);
}

My question is, how to do this, and what should the function ..... operator[](const int & rhs);我的问题是,如何做到这一点,以及应该使用什么函数..... operator[](const int & rhs); return?返回?

FYI I am not using the array container directly because I am implementing other functions also I am doing the matrix column major.仅供参考,我没有直接使用数组容器,因为我正在实现其他功能,我也在做矩阵列专业。

Doesn't this work?这不行吗?

  std::array<float, 3>& operator[](const int & rhs) {
    return matrix[rhs];
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM