首页 > 解决方案 > 如何重载下标运算符 [] 以引用 2d STL 数组?

问题描述

我正在尝试为我的类创建一个重载运算符,我的类包含一个二维数组容器。我想按如下方式使用运算符: fooClass a; a[i][j] = 4; 我不想像 a[i, j], a(i, j) 那样使用它,也不想调用函数来输入或输出元素。有可能吗?

链接调用不起作用,因为第一个返回指向数组的指针,第二个应该返回数组中的一个元素,即浮点数。

我的课看起来像这样:

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);
}

我的问题是,如何做到这一点,函数应该..... operator[](const int & rhs);返回什么?

仅供参考,我没有直接使用数组容器,因为我正在实现其他功能,我也在做矩阵列专业。

标签: c++arraysstloperator-overloading

解决方案


这不行吗?

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

推荐阅读