C++ overload operator [ ][ ]

后端 未结 5 1894
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 12:35

I have class CMatrix, where is \"double pointer\" to array of values.

class CMatrix {
public:
    int rows, cols;
    int **arr;
};

I simpl

5条回答
  •  忘掉有多难
    2020-11-28 12:55

    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;
    };
    

提交回复
热议问题