C++ multidimensional array operator

后端 未结 7 1369
栀梦
栀梦 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

    As mentionned before, there is no such thing as operator[][]. However, here is an an implementation using nested classes similar to what "jalf" proposed. For sake of simplicity, I hardcoded a 3x3 raw array.

        class Array2D final{
        public:
            class PartialArr final{
        private:
            friend Array2D;
            PartialArr(Array2D* ptr, int index) :original(ptr), firstIndex(index) {}
            int firstIndex;
            Array2D* original;
        public:
            int& operator[](int index) { return this->original->data[firstIndex][index];  }
        };
    
            PartialArr operator[](int index) { return PartialArr(this, index); }
        private:
            int data[3][3];
        };
    
    

    This solution prevents the user of Array2D to manipulate the data directly when indexing only the first dimension of the array.

    const versions of both operator[] could also be added to make the class complete.

提交回复
热议问题