Analysis of subscript overloading of multidimensional arrays

  • 2020-04-02 01:34:45
  • OfStack

Today I saw someone ask how to overload an operation symbol like [][] in a 2-dimensional or multidimensional array.

In fact, the idea is not difficult ah, it is just overloading 2 [] symbols, and 2 [] function is different.

The first [] should locate the row.

The last [] should return a reference to the final data.

Post the code to achieve the basic functions, such as detection, and other functions are not written, as long as the reflection of the train of thought, other functions good plus.


#include <iostream> 
#include <string>
using namespace std;
template <class T> class arr;
template <class T> class arrBody
{
    private:
    friend class arr<T>;
    T* data;
    int row,col,current_row;
    arrBody(int r,int c,T d):row(r),col(c)
    {
        data=new T[r*c];
        current_row=-1;
        for(int k=0;k<r*c;k++)              //Initializes the data, which defaults to 0
            data[k]=d;
    }
    public:
        T&   operator[](int  j)            //Overload the second [] sign
        {
            if(j>=0&&j<col)
                return data[current_row*col+j];
        }
        ~arrBody(){delete[]data;} }; template <class  T>  class arr   
{   
private:
    arrBody<T> tBody;   
public:   
    arrBody<T>  &operator[](int i)         //Reload the first [] sign
    {
        if(i>=0&&i<tBody.row)
            tBody.current_row=i;
        return tBody;
    }
    arr(int  i,int  j,T d=0):tBody(i,j,d) {}   
};

void main()
{
    arr<int> a(10,20);
    arr<double> b(5,5);
    cout<<a[5][5]<<endl;
}


Related articles: