C++ overload operator [ ][ ]

倖福魔咒の 提交于 2019-11-27 01:45:51

You cannot overload operator [][], but the common idiom here is using a proxy class, i.e. overload operator [] to return an instance of different class which has operator [] overloaded. For example:

class CMatrix {
public:
    class CRow {
        friend class CMatrix;
    public:
        int& operator[](int col)
        {
            return parent.arr[row][col];
        }
    private:
        CRow(CMatrix &parent_, int row_) : 
            parent(parent_),
            row(row_)
        {}

        CMatrix& parent;
        int row;
    };

    CRow operator[](int row)
    {
        return CRow(*this, row);
    }
private:
    int rows, cols;
    int **arr;
};

There is no operator[][] in C++. However, you can overload operator[] to return another structure, and in that overload operator[] too to get the effect you want.

You can do it by overloading operator[] to return an int*, which is then indexed by the second application of []. Instead of int* you could also return another class representing a row, whose operator[] gives access to individual elements of the row.

Essentially, subsequent applications of operator[] work on the result of the previous application.

If you create a matrix using Standard Library containers, it's trivial:

class Matrix {
    vector<vector<int>> data;

public:
    vector<int>& operator[] (size_t i) { return data[i]; }
};

You could operator[] and make it return a pointer to the respective row or column of the matrix. Because pointers support subscripting by [ ], access by the 'double-square' notation [][] is possible then.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!