Operator overloading [] [] 2d C ++ array

I have a 2D array and I want to define a function that returns the index value that the user gives me using operator overloading. In other words:

void MyMatrix::ReturnValue() { int row = 0, col = 0; cout << "Return Value From the last Matrix" << endl; cout << "----------------------------------" << endl; cout << "Please Enter the index: [" << row << "][" << col << "] =" << ((*this).matrix)[row][col] << endl; } 

The operation ((*this).matrix)[row][col] should return an int . I have no idea how to build operator [][] .
Alternatively, I could concatenate a couple of calls to operator [] , but I didn’t succeed because the first call of this operand will return int* , and the second will return int , and it will force to create another operator, and I do not want to do this.

What can I do? Thanks,

+5
source share
2 answers

It just doesn’t exist , so you cannot overload it.

A possible solution is to define two classes: Matrix and String.
You can define operator[] for Matrix to return Row and then define the same operator for Row to return the actual value ( int or whatever you want, your Matrix can also be a template).
Thus, the statement myMatrix[row][col] will be legal and meaningful.

You can do the same to assign a new Row a Matrix or change the value in Row .

* EDIT *

As pointed out in the comments, you should also accept to use operator() instead of operator[] for such a case. Thus, there will no longer be a need for the Row class.

+6
source

You can define your own operator [] for the class. A direct approach might look like this.

 #include <iostream> #include <iomanip> struct A { enum { Rows = 3, Cols = 4 }; int matrix[Rows][Cols]; int ( & operator []( size_t i ) )[Cols] { return matrix[i]; } }; int main() { A a; for ( size_t i = 0; i < a.Rows; i++ ) { for ( size_t j = 0; j < a.Cols; j++ ) a[i][j] = a.Cols * i + j; } for ( size_t i = 0; i < a.Rows; i++ ) { for ( size_t j = 0; j < a.Cols; j++ ) std::cout << std::setw( 2 ) << a[i][j] << ' '; std::cout << std::endl; } } 

Program exit

  0 1 2 3 4 5 6 7 8 9 10 11 
+2
source

Source: https://habr.com/ru/post/1239192/


All Articles