Solved

overloading the [] operator

Posted on 1998-04-08
13
288 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 100 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
Independent Software Vendors: 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!

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

733 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