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




freyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

nietodCommented:
answer coming.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
vsinhaCommented:
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.
0
nietodCommented:
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.
0
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

nietodCommented:
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.
0
nietodCommented:
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.
0
alexoCommented:
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.
0
nietodCommented:
Picky, picky, picky...
That's the nature of templates.  I was referring to source and maintenance complexity.
0
alexoCommented:
True.  

(About the source complexity--not about my being picky!)
0
nietodCommented:
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 ?


0
freyAuthor Commented:
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?
0
nietodCommented:
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;


                        
0
freyAuthor Commented:
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.
   }
};
0
nietodCommented:
I forgot half.  You need to make the matrix's operator [] return the xReference class.

xReference matrix::operator [] (int X)
{
   return xReference(this,x);
};
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.