C++ multidimensional array operator

后端 未结 7 1375
栀梦
栀梦 2021-01-05 16:22

it is possible to overload somehow operator for multidimensional array?

Something like:

class A {
  ...
  int& operator[][] (const int x, const i         


        
7条回答
  •  日久生厌
    2021-01-05 16:54

    Not directly, but you can achieve the same functionality overloading operator[]() and having it return something that supports operator[]() itself.

    For example:

    class A {
      std::vector > vec;
    public:
      std::vector& operator[] (int x)
      {
          return vec[x];
      }
    };
    

    would allow you to write:

    A a;
    //...
    int y = a[1][2];
    

    because a[1] returns a std::vector to which you can apply operator[](2).

提交回复
热议问题