Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Overloading [] operator for two dimensional array: How?

Status
Not open for further replies.

Ricardo

MIS
Jan 16, 1999
5
UY
Greetings, I need help to resolve this problem...

I have a class like this:

class CRealMatrix
{
private:
double m_RealMat[MAX][MAX];
}


I want to overload the [] operator, so I can access the elements of m_RealMat[][] as l-values, applying the subscript operator directly to the object. For instance:

CRealMatrix m;
m[1][1] = 1.5;


Is it possible to overload the [] operator for multidimensional arrays? How it can be done?

Thanks a lot!
Ricardo.-
 
The [] operator can be overloaded so that the array may be used as an lvalue. Instead why can't you do:
CRealMatrix* pTemp;
pTemp = new CRealMatrix;
pTemp->m_RealMatix [1][1] = 1.5;

Not sure this helps.
JC
 
Thanks JC. One of the reasons I'm trying to overload the [] operator is that I would like to index the matrix from 1 to MAX, instead of 0 to MAX-1 (this would be the case using common arrays). This object will be use in an already wrote scientific code that indexes arrays from 1 to N, so I would like to "mask" the indexing in the overload function, too.

So can it be done for multiple dimension arrays? How?

Thanks,
Ricardo.-
 
Ricardo,

The code I am posting is only in reference to your question How. I am not advising you to take this approach. I do suggest you read the latest volume of Effective C++ by Scott Meyers. Anyway, for what it is worth, here is some code that works, you will need to adjust for the 1 based operations.


#include <vector>
#include <iostream>

typedef std::vector<double> DOUBLEV;

class MatrixRow{
DOUBLEV _values;

public:
MatrixRow(){
}

double&amp; operator[](int nIndex){
resize(nIndex + 1);
return _values[nIndex];
}

protected:
void resize(int n){
if ( _values.size() < n)
_values.resize(n, 0.0);
}
};

typedef std::vector<MatrixRow> MATRIXROWS;
class Matrix{

MATRIXROWS _rows;

public:
Matrix(int rows, int cols){
resize(rows);
for(int n=0; n<rows; n++)
_rows[n][cols -1];
}

MatrixRow&amp; operator[](int nIndex){
resize(nIndex + 1);
return _rows[nIndex];
}

protected:
void resize(int n){
if ( _rows.size() < n)
_rows.resize(n);
}
};

void main(int argc, char* argv[]){

Matrix m(3,3);
std::cout << &quot;2,2: &quot; << m[2][2] << std::endl;
m[5][5] = 4.5;
std::cout << &quot;5,5: &quot; << m[5][5] << std::endl;


Hope this helps
-pete
 
palbano,

You'll be interested to know that in the sequel to Effective C++ meyers actually has an article describing exactly what you suggested. ;)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top