Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

matrix - C++ overload operator [ ][ ]

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

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

I simply need to access the values of matrix by typing:

CMatrix x;
x[0][0] = 23;

I know how to do that using:

x(0,0) = 23;

But I really need to do that the other way. Can anyone help me with that? Please?

Thank you guys for help at the end I did it this way...

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

public:
   int const* operator[]( int const y ) const
   {
      return &arr[0][y];
   }

   int* operator[]( int const y )
   {
      return &arr[0][y];
   }

   ....

Thank you for your help I really appreciate it!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...