问题
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!
回答1:
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;
};
回答2:
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.
回答3:
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.
回答4:
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]; }
};
回答5:
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.
来源:https://stackoverflow.com/questions/15762878/c-overload-operator