Solved

overloading the [] operator

Posted on 1998-04-08
13
267 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
  • 8
  • 2
  • 2
  • +1
13 Comments
 
LVL 22

Accepted Solution

by:
nietod earned 100 total points
Comment Utility
answer coming.
0
 
LVL 1

Expert Comment

by:vsinha
Comment Utility
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
Comment Utility
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
 
LVL 22

Expert Comment

by:nietod
Comment Utility
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
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 22

Expert Comment

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

Expert Comment

by:alexo
Comment Utility
True.  

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

Expert Comment

by:nietod
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
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.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

762 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now