Link to home
Start Free TrialLog in
Avatar of frey
frey

asked on

overloading the [] operator

matrice::matrice(int lgne,int col)
{

      ligne=lgne;
      colonne=col;
      cell=new (int*[lgne]) ;
      for(int i=0;i<lgne;i++)
            cell[i]=new int[col];
      
}


This is the constructor for my matrix class, I can use my matrix like a multidimensional table, I would like to overload the [ ] operator to perform a check if the asked cell is within the matrix.

If I call the element [4][3], how can I overload my operator[] function 0,in order to check the valifity of the element ?  The [ ] operator does only accept one argument.

                                                                                Thanks




ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of vsinha
vsinha

There are three ways.  The first two are a little more straighforward but do not yield syntaxes that look C's typical array access syntax, that is [x][y].  The final way does work like that, but is a little harder and I personally don't feel it is worth it.

The easy way is to not use operator [].  Use operator () instead because it can take multiple parameters.  So just declare an overloaded operator () that takes two integer parameters.  

However, if you insist on using two operator [], there are two ways.  The first way is to pass a type that indicates the two values.  For example, you could create a class that specifies the row and column like.

class Position
{
public:
   int row;
   int col;
   Pos(int R, int C) : row(R), col(c) {};
}

The make operator [] accept a position object.  You can call operator [] using a syntax like
SomeMatrix[Position(5,4)];

It you don't like that, there's one other way that yields the standard C syntax.  I'll send it next.
To get the standard syntax you need to overload operator [] to return a class that indicates an entire row (or column).  The overload operator [] on that class to return a single cell in the row (or column).  Something like


class matrix
{
   class matixrow
  {
      int row
     int operator [] (int Col);
  }
  matixrow operator [] (int row);
}


I can provide more details if you let me know what sort of solution you want.
I see vshina put in a comment.  He has the right idea (like my 3rd suggestion), he said that you have to overload operator [] twice.  But he doesn't point out that it is overloaded once for the matrix class and once for another class, that is returned by the matix's overload.
nietod's "third" suggestion is the preferred way because usually matrices are used along with vectors and the matrix::operator[] can just return a vector.
Also, you can use a vector of vectors (templates help here), thus no need to keep two classes.
Actually, even if you use a "vector of vector" you will still have two different classes.  Its just that the two classes were generated from the same template, but they still are distinct classes.
Picky, picky, picky...
That's the nature of templates.  I was referring to source and maintenance complexity.
True.  

(About the source complexity--not about my being picky!)
OK, your advice is great, but I still got a big problem, to simplify,if i define the following vector class :
class vector
{
public:
      int nbElements;
      int *cell;
      vector();
      vector(int nb);
      ~vector();
      int operator[](int element);
      
};


int vector::operator[](int element)
{
      return cell[element];
}

my test program looks like this :

void main()
{
      vector vc1(5);
      vc1[1]=3; // left operand is not a l-value error message
      vc1.cell[1]=3; // OK
      int vc2[6];
      vc2[3]=5; // OK
}

I know that this code cannot work, because vc1[1] return an int value and can consequently not be used as an l-value.
 
Even if I overload the [ ] operator (void type) in order to assign a value to an element, how can the program detect which one to use ?
I will get the overloaded function only differs by it's return value error msg.

Is there a way to solve this problem ?


Avatar of frey

ASKER

First of all, do you want to make this work just your 2D matrices or do you want to use the sort of solution that alexo suggested.  That solution uses templates to create 1 dimensional arrays.  But since the arrays are templates your can create arrays of many different types.  To create your 2D matrices you create a 1D array of a 1D array of integers.  The advanatage of this technique is that it more flexible.  you can create arrays of other things (not just integers) and you can create arrays that 3 or more dimensions as well.  The dissadvantage is the programming is slightly more cumbersome.  Another disadvantage might be that your matric is now implimented as an array of an array of integers.  That might have some impact on what you are hoping to accomplish.

So which way do you want to go?
I would like to use the following constructor, because I don't know how to use templates


matrice::matrice(int lne,int col)
    {

    line=lne;
    column=col;
    cell=new (int*[lne]) ;
    for(int i=0;i<lne;i++)
    cell[i]=new int[col];

    }

matrix.h contain the following declaration of memeber variables :
 
int **cell;
int line,column;


                        
Avatar of frey

ASKER

Okay.  That's the easier, but less advanced way.  
I'm assuming that two [] operators go in xy order (that is, it is [x][y], not [y][x]).  If not you have to reverse x and y in everything I say!

You will need to create a new class Say XReference  It will store the X values specified to [] and a pointer back to the matrix. It will need a [] operator that does the final logic.  It should look something like this.

class xReference
{
   matrice *MatricPtr;
   int          X;
   // constuctor.
   xReference(matrice *Mptr,
                    int         IniX) :
    MatricPtr(MPtr),
    X(IniX)
    { }:
   // the important function.
   int operator [] (int Y)
   {
      return MatricPtr->GetCell(X,Y);
     // Not I assume you have some function in class matrice to get a cell.  If not, this
     // class could be declared as a friend and could obtain it itself.
   }
};
I forgot half.  You need to make the matrix's operator [] return the xReference class.

xReference matrix::operator [] (int X)
{
   return xReference(this,x);
};