lundi 4 janvier 2016

How would I create two matrices (all values Ones or values Zeros) using static member functions which call the same constructor?

So basically the way my program works for using a static member function to request a 2x4 matrix of Zeros proceeds as follows:

Matrix Matrix::Zeros (const int noOfRows, const int noOfCols){
    Matrix outZ(noOfRows, noOfCols);
    return outZ;
} //My static Zeros member function

This was referring to my constructor which stores zero values in a 2x4 matrix as follows:

Matrix::Matrix (const int noOfRows, const int noOfCols){

this->noOfRows = noOfRows;
this->noOfCols = noOfCols;

data = new double[noOfRows*noOfCols];
    for(int i=0; i< noOfRows*noOfCols; i++){
        data[i] = 0;
    }
}

My issue is that I want to call this same constructor to request a 2x4 matrix of Ones using the following static member function:

Matrix Matrix::Ones(const int noOfRows, const int noOfCols){
    Matrix outO(noOfRows, noOfCols);
    return outO;
} //My static Ones member function

This obviously returns a 2x4 matrix of Zeros and not Ones. Therefore, I have been trying to figure out a way to have an if statement within my constructor so that it will create a matrix of Zeros or Ones based on the object name I am returning in my static member function i.e.

if(outZ){
    for(int i=0; i< noOfRows*noOfCols; i++){
        data[i] = 0;
    }
}

if(outO){
    for(int i=0; i< noOfRows*noOfCols; i++){
        data[i] = 1;
    }
}

Is this possible or is there a better alternative for implementing this if statement? (I am limited in this format as I need to use the data variable since I use it later during operator<< overloading)

Aucun commentaire:

Enregistrer un commentaire