C++ overload operator [ ][ ]

后端 未结 5 1877
佛祖请我去吃肉
佛祖请我去吃肉 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:38

    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.

    0 讨论(0)
  • 2020-11-28 12:39

    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.

    0 讨论(0)
  • 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;
    };
    
    0 讨论(0)
  • 2020-11-28 12:55

    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.

    0 讨论(0)
  • 2020-11-28 12:55

    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]; }
    };
    
    0 讨论(0)
提交回复
热议问题