-1

so currently i have to write a program in c++ where i have to create a class "CMyMatrix" and i wanted to know if its possible to overload the operator: "[][]"(i think technically they are 2 operators?) im using a 2d vector and would like the operator to work the same way as it works if you create a 2d array.

class CMyMatrix {
private:
    std::vector<std::vector<double>> matrix;
    int row_M = 0;
    int column_N = 0;
public:
    double& operator[][](int M, int N) { return something };
};

thank you for any help in advance.

Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
  • 1
    There's no `operator[][]()` function, you could overload directly. – πάντα ῥεῖ Apr 29 '22 at 11:04
  • You could have `operator[]` return a proxy object that has its own `operator[]` that accesses the underlying member variable. Alternatively, you could use `operator()(int M, int N)` if accessing it as a functor is acceptably. And if C++23, see the answer below. – Eljay Apr 29 '22 at 11:11
  • You might want to consider what would happen if your `CMyMatrix` class simply had `std::vector &operator[] (int M) { return matrix[M]; }`. – G.M. Apr 29 '22 at 11:19

1 Answers1

2

This couldn't be done before C++23 since operator[] must have exactly one argument.

With the adoption of the multidimensional subscript operator in C++23, now you can

#include <vector>

class CMyMatrix {
private:
    std::vector<std::vector<double>> matrix;
    int row_M = 0;
    int column_N = 0;
public:
    double& operator[](int M, int N) { return matrix[M][N]; };
};

int main() {
  CMyMatrix m;
  m[0, 1] = 0.42;
}

Demo

康桓瑋
  • 33,481
  • 5
  • 40
  • 90