So I believe I'm on the right track here but I'm not the best when it comes to C++. I need to overload the [] operator for a Matrix class. The project and code is very long so I'll just include the important parts here you can assume I have constructors and other functions working correctly.
//Matrix.h
#include <string>
#include <ostream>
// Type definitions
typedefdouble Element_t; //Data type inside the "matrix"
typedefunsignedint Index_t; //Data type used for indexing
class Matrix
{
public:
Element_t* operator[](Index_t index) const; // I cannot change this
private:
// Matrix dimensions
Index_t nRows;
Index_t nCols;
// Array to hold matrix data
// 2D matrix is stored in a 1D array
// mat[i][j] = elements[i*nCols+j];
Element_t *elements;
};
My thoughts here are that "elements" is a one dimensional array holding a 2D matrix. So if I wanted to point to the [i]th row I would take "index" and multiply that by "nCols" and return that array as a pointer to that index. So when I call something like:
mat[i][j]
The overloaded operator would return the index to the [i]th row and then the [] operator would return the [j]th "element" after that.
Now that I've typed all this up I think I see my problem. I'm returning 1 element of the array in my code and not a whole "row" like if I had a matrix:
1 2 3
4 5 6
7 8 9
and I wanted mat[1][2] my code is only returning a pointer to "4" the first time and not to the whole row? But I thought the pointer could only point to one element in an array...so now I'm confusing myself. Because the "elements" are stored like:
Elements_t elements = {1,2,3,4,5,6,7,8,9};
So it points to 4 and then the 2nd [] operator does nothing in a sense? As you can tell I'm a little confused with pointers and references. Any advice would be really appreciated.
Ha ok. Thanks. I guess I'm doing something else wrong because its not implementing right. I guess I get to spend hours trying to figure out what the problem is. Thanks for the help.