2

Need help

I am new to the operators overloading , and now am trying to initialize a matrix by using operators [][] overloads. I would like to initialize the matrix using the following way : matrix [0][0] =100

is it possible to use [][] ? how do i use them ?

 //main.cpp//
 void main()
    {
        Matrix m(2, 2);
        m[0][0] = 2;
    }


//matrix.h//
#ifndef MATRIX_H
#define MATRIX_H


class Matrix
{
public :
    Matrix(int ,int );
    Matrix operator [][] // *****im stuck here*****


private : 
    int numRows;
    int numCols;
    int **matrix;  
}
#endif


//matrix.cpp//

#include <iostream>
#include "Matrix.h"
using namespace std;


Matrix::Matrix(int rows,int cols)
    :numOfCols(cols),numOfRows (rows)
{
    matrix=new int *[cols];
    for(int i=0;i<rows;i++)
    {
        matrix[i]=new int [cols];
        for(int c=0;c<cols;c++)
        {
            matrix[i][c]=0;
        }


    }
}
Wemos
  • 61
  • 1
  • 9
  • Instead of writing all this code, why not just use `std::array, rowCount>`? You still get `foo[y][x]` syntax. – Jack Deeth Dec 11 '16 at 02:42
  • @Jack Deeth bad idea if ne needs a gapless array of values, e.g. to use somewhere else. bad idea from performance POV too. and it that's an education exercise - that won't cut it. – Swift - Friday Pie Dec 11 '16 at 03:33

1 Answers1

2

There are a number of ways of doing this, here's one I prepared earlier, which uses a proxy class to represent the rows. Please note is won't be particularly performant, and doesn't implement copy/assignment/move etc.

#include <iostream>
using namespace std;


class Mat2 {

    public:

        Mat2( unsigned int x, unsigned int y ) :
            mX(x), mY(y), mData( new int[x * y] ) {}

        ~Mat2() { 
            delete [] mData; 
        }


        int & At( unsigned int x ,unsigned int y ) {
            return mData[ x * mY + y ];
        }

        class XProxy {
            public:
                XProxy( unsigned int x, Mat2 * mat ) :mX(x), mMat(mat) {}
                int & operator[]( unsigned int y ) {
                    return mMat->At( mX, y );
                }
            private:
                unsigned int mX;
                Mat2 * mMat;
        };


        XProxy operator[]( unsigned int x)  {
            return XProxy(x, this);
        }

    private:

        unsigned int mX, mY;
        int * mData;

};

int main() {
    Mat2 m(4,6);
    m[1][3] = 42;
    cout << m.At( 1, 3 ) << endl;
}