?
Solved

overloading the [] operator

Posted on 1998-04-08
13
Medium Priority
?
304 Views
Last Modified: 2010-04-10
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




0
Comment
Question by:frey
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 2
  • 2
  • +1
13 Comments
 
LVL 22

Accepted Solution

by:
nietod earned 400 total points
ID: 1184127
answer coming.
0
 
LVL 1

Expert Comment

by:vsinha
ID: 1184128
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
 
LVL 22

Expert Comment

by:nietod
ID: 1184129
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 22

Expert Comment

by:nietod
ID: 1184130
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
 
LVL 22

Expert Comment

by:nietod
ID: 1184131
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
 
LVL 11

Expert Comment

by:alexo
ID: 1184132
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
 
LVL 22

Expert Comment

by:nietod
ID: 1184133
Picky, picky, picky...
That's the nature of templates.  I was referring to source and maintenance complexity.
0
 
LVL 11

Expert Comment

by:alexo
ID: 1184134
True.  

(About the source complexity--not about my being picky!)
0
 
LVL 22

Expert Comment

by:nietod
ID: 1184135
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
 

Author Comment

by:frey
ID: 1184136
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
 
LVL 22

Expert Comment

by:nietod
ID: 1184137
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
 

Author Comment

by:frey
ID: 1184138
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
 
LVL 22

Expert Comment

by:nietod
ID: 1184139
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

719 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question