Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two square bracket overloading

I am writing a matrix class in c++ and trying to overload some operator like = and >> and << etc.

I was unable to overload operator [][] for matrix class. if i have an object of class matrix like M1 then i can use this way for giving value to each element:

M1[1][2]=5;

OR

int X;

X=M1[4][5];
like image 222
fafa Avatar asked Apr 12 '11 14:04

fafa


Video Answer


2 Answers

I am exactly working on a matrix class and I decided to first create an Array class which has a dynamic 2-D array. So, well just as you, I confronted this obstacle that how I can overload two square brackets. How I approached this case is very simple; I overloaded the square brackets operator twice as member functions. First, I overloaded [] so as to return a pointer pointing to the desired row, so to speak, and then the following member function (i.e. again operator [] overloaded) returns a lvalue of the same type as the array's elements.

However, note that the index you inter to invoke the former overloaded operator [] must be saved somewhere so that you may use it in the latter overloaded operator []. For this reason I simply added a new member of the type int to the class Array (which I've named it "test" in my code below).

class Array {

private: 

 double **ptr; int test;
 ...   /* the rest of the members includes the number of rows and columns */

public:
    Array(int=3,int=3);  // Constructor
    Array(Array &);      // Copy Constructor
    ~Array();            // Destructor
    void get_array();
    void show_array();
    double* operator[] (int);
    double operator[] (short int);
    ...
};

... 

double* Array::operator[] (int a) {
    test = a;
    double* p = ptr[test];
    return p;
}

double Array::operator[] (short int b) {
   return ((*this)[test][b]);
}

Therefor, as an example, in main I can simply write:

int main(){
Array example;
cout << example[1][2];  
}

I hope this would help you.

like image 53
sina shokri Avatar answered Sep 18 '22 03:09

sina shokri


You could overload operator[]. So if you would like to use matrix that way, you should make matrix as array of vectors.

class Matrix
{
...
  Vector & operator[]( int index );
...
};

and

class Vector
{
...
  double & operator[]( int index );
...
};

Finally:

Matrix m;
...
double value = m[i][j];
...
like image 44
Naszta Avatar answered Sep 22 '22 03:09

Naszta